JosepRivaille

P13994: Weighted shortest path (2)

May 19th, 2016
480
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <stack>
  4. #include <queue>
  5. #include <limits>
  6. using namespace std;
  7.  
  8. typedef vector< pair<int, int> > Adj; // Distance - node
  9. typedef vector<Adj> Graph;
  10.  
  11. typedef int boolean;
  12.  
  13. void dijkstra(Graph &G, int u, int v)
  14. {
  15.   int n = G.size();
  16.   vector<int> distance(n, numeric_limits<int>::max()); // Infinite
  17.   distance[u] = 0;
  18.   vector<boolean> visited(n, false);
  19.   vector<int> whereFrom(n, -1);
  20.   priority_queue< pair<int, int>, vector< pair<int, int> >, greater< pair<int, int> > > pQ;
  21.   pQ.push({0, u});
  22.   while (!pQ.empty() && pQ.top().second != v) {
  23.     int new_node = pQ.top().second;
  24.     pQ.pop();
  25.     if (!visited[new_node]) {
  26.       visited[new_node] = true;
  27.       for (int i = 0; i < G[new_node].size(); ++i) {
  28.     pair<int, int> aux = G[new_node][i];
  29.     if (distance[new_node] + aux.first < distance[aux.second]) {
  30.       distance[aux.second] = distance[new_node] + aux.first;
  31.       whereFrom[aux.second] = new_node;
  32.       pQ.push({distance[aux.second], aux.second});
  33.     }
  34.       }
  35.     }
  36.   }
  37.   if (pQ.empty()) {
  38.     cout << "no path from " << u << " to " << v << endl;
  39.     return;
  40.   }
  41.   stack<int> result;
  42.   while (whereFrom[v] != -1) {
  43.     result.push(v);
  44.     v = whereFrom[v];
  45.   }
  46.   result.push(v);
  47.   cout << result.top(); result.pop();
  48.   while (!result.empty()) {
  49.     cout << " " << result.top();
  50.     result.pop();
  51.   }
  52.   cout << endl;
  53. }
  54.  
  55. int main()
  56. {
  57.   int n, m, u, v, c;
  58.   while (cin >> n >> m) {
  59.     Graph G(n);
  60.     for (int i = 0; i < m; ++i) {
  61.       cin >> u >> v >> c;
  62.       G[u].push_back({c, v});
  63.     }
  64.     cin >> u >> v;
  65.     dijkstra(G, u, v);
  66.   }
  67. }
  68.  
  69. //JosepRivaille
Add Comment
Please, Sign In to add comment