BotByte

dijkstra.cpp

Feb 26th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. /***Dijkstra's Algorithm***/
  2.  
  3. #include <bits/stdc++.h>
  4.  
  5. using namespace std;
  6. typedef pair<long long, int> PII;
  7. #define MAX 1000
  8. vector<PII> adj[MAX];
  9. bool marked[MAX];
  10. int dist[MAX];
  11.  
  12. void dijkstra(int s)
  13. {
  14.     priority_queue<PII, vector<PII>, greater<PII> > pq;
  15.     memset(marked, false, sizeof marked);
  16.     for(int i=1; i<MAX; i++) dist[i] = 1e9;
  17.  
  18.     PII p;
  19.     pq.push(make_pair(0, s));
  20.     dist[s] = 0;
  21.  
  22.     while(!pq.empty()){
  23.         p = pq.top();
  24.         pq.pop();
  25.  
  26.         int u = p.second;
  27.         int cost_u = p.first;
  28.         if(marked[u]) continue;
  29.  
  30.         marked[u] = true;
  31.  
  32.         for(int i=0; i<adj[u].size(); i++){
  33.             int cost_u_to_v = adj[u][i].first;
  34.             int v = adj[u][i].second;
  35.             if(dist[v] > cost_u + cost_u_to_v){
  36.                  dist[v] = cost_u + cost_u_to_v;
  37.                  pq.push(make_pair(dist[v], v));
  38.             }
  39.         }
  40.     }
  41. }
  42.  
  43. int main()
  44. {
  45.     int nodes, edges;
  46.     scanf("%d %d", &nodes, &edges);
  47.     for(int i=0; i<edges; i++){
  48.         int u, v, w;
  49.         scanf("%d %d %d", &u, &v, &w);
  50.         adj[u].push_back(make_pair(w, v));;
  51.     }
  52.     dijkstra(0);
  53.     for(int i=1; i<MAX; i++) printf("%d %d\n", i, dist[i]);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment