Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <queue>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. typedef pair<int, int> WArc;
  8. typedef vector<vector<WArc>> WGraph;
  9.  
  10. using VE = vector<int>;
  11.  
  12. void dijkstra(const WGraph& G, int s, vector<int>& d, vector<int>& p) {
  13.    
  14.     int n = G.size();
  15.     d = vector<int>(n, 10000000);
  16.     d[s] = 0;
  17.     p = vector<int>(n, -1);
  18.     vector<bool> S(n, false);
  19.     priority_queue<WArc, vector<WArc>, greater<WArc> > Q;
  20.     Q.push(WArc(0, s));
  21.  
  22.     while (not Q.empty()) {
  23.         int u = Q.top().second; Q.pop();
  24.         if (not S[u]) {
  25.             S[u] = true;
  26.             for (WArc a : G[u]) {
  27.                 int v = a.second;
  28.                 int c = a.first;
  29.  
  30.                 if (d[v] > d[u] + c) {
  31.                     d[v] = d[u] + c;
  32.                     p[v] = u;
  33.                     Q.push(WArc(d[v], v));
  34.                 }
  35.             }
  36.         }
  37.     }
  38. }
  39.  
  40. int main(){
  41.  
  42.     int n,m;
  43.     while (cin >> n >> m) {
  44.         WGraph G(n);
  45.         //Read the matrix
  46.         for (int r = 0; r < m; ++r) {
  47.             int x,y,z;
  48.             cin >> x >> y >> z;
  49.             pair<int,int> pi = make_pair(z,y);
  50.             G[x].push_back(pi);
  51.         }
  52.  
  53.         int a, b;
  54.         cin >> a >> b;
  55.  
  56.         VE p,d;
  57.  
  58.         dijkstra(G,a,p,d);
  59.  
  60.         if (d[b] != -1) cout << p[b] << endl;
  61.         else cout << "no path from " << a << " to " << b << endl;
  62.         //for (int i = 0; i < p.size(); ++i) cerr << i << ": " << p[i] << endl;
  63.  
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement