Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <queue>
- #include <iostream>
- #include <vector>
- using namespace std;
- typedef pair<int, int> WArc;
- typedef vector<vector<WArc>> WGraph;
- using VE = vector<int>;
- void dijkstra(const WGraph& G, int s, vector<int>& d, vector<int>& p) {
- int n = G.size();
- d = vector<int>(n, 10000000);
- d[s] = 0;
- p = vector<int>(n, -1);
- vector<bool> S(n, false);
- priority_queue<WArc, vector<WArc>, greater<WArc> > Q;
- Q.push(WArc(0, s));
- while (not Q.empty()) {
- int u = Q.top().second; Q.pop();
- if (not S[u]) {
- S[u] = true;
- for (WArc a : G[u]) {
- int v = a.second;
- int c = a.first;
- if (d[v] > d[u] + c) {
- d[v] = d[u] + c;
- p[v] = u;
- Q.push(WArc(d[v], v));
- }
- }
- }
- }
- }
- int main(){
- int n,m;
- while (cin >> n >> m) {
- WGraph G(n);
- //Read the matrix
- for (int r = 0; r < m; ++r) {
- int x,y,z;
- cin >> x >> y >> z;
- pair<int,int> pi = make_pair(z,y);
- G[x].push_back(pi);
- }
- int a, b;
- cin >> a >> b;
- VE p,d;
- dijkstra(G,a,p,d);
- if (d[b] != -1) cout << p[b] << endl;
- else cout << "no path from " << a << " to " << b << endl;
- //for (int i = 0; i < p.size(); ++i) cerr << i << ": " << p[i] << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement