JosepRivaille

P43859: Weighted shortest path (1)

May 10th, 2016
506
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5.  
  6.  
  7. typedef pair<int, int> node_distance; // First -> Weight | Second -> Node
  8. typedef vector< vector<node_distance> > Graph;
  9. typedef int boolean;
  10.  
  11. int dijkstra(const Graph &G, int x, int y)
  12. {
  13.     vector<boolean> visited(G.size(), false);
  14.     vector<int> distance(G.size(), -1); // We consider -1 as infinite
  15.     priority_queue< node_distance, vector<node_distance>, greater<node_distance> > pQ;
  16.     pQ.push({0, x});
  17.     distance[x] = 0;
  18.     while (!pQ.empty()) {
  19.         int current_node = pQ.top().second;
  20.         pQ.pop();
  21.         if (!visited[current_node]) {
  22.             visited[current_node] = true;
  23.             for (int i = 0; i < G[current_node].size(); ++i) {
  24.                 node_distance aux = G[current_node][i];
  25.                 if (distance[aux.second] == -1 || distance[aux.second] > distance[current_node] + aux.first) {
  26.                     distance[aux.second] = distance[current_node] + aux.first;
  27.                     pQ.push({distance[aux.second], aux.second});
  28.                 }
  29.             }
  30.         }
  31.     }
  32.     return distance[y];
  33. }
  34.  
  35. int main()
  36. {
  37.     int n, m;
  38.     while (cin >> n >> m) {
  39.         Graph G(n);
  40.         int u, v, c;
  41.         for (int i = 0; i < m; ++i) {
  42.             cin >> u >> v >> c;
  43.             G[u].push_back({c, v});
  44.         }
  45.         int x, y;
  46.         cin >> x >> y;
  47.         int result = dijkstra(G, x, y);
  48.         if (result == -1) cout << "no path from " << x << " to " << y << endl;
  49.         else cout << result << endl;
  50.     }
  51. }
  52.  
  53. //JosepRivaille
Add Comment
Please, Sign In to add comment