Advertisement
istinishat

dijkstra

Jun 3rd, 2016
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstring>
  4. #include <queue>
  5. #include <vector>
  6. #include <algorithm>
  7.  
  8. using namespace std;
  9.  
  10. #define si(a) scanf("%d",&a)
  11. #define f first
  12. #define s second
  13. #define mp(a,b) make_pair(a,b)
  14. #define MAX 1005
  15.  
  16. int dist[MAX];
  17. vector<pair<int,int> > graph[MAX];
  18.  
  19. void dijkstra(int st)
  20. {
  21.     priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > Q;
  22.     Q.push(mp(0,st));
  23.     memset(dist,-1,sizeof(dist));
  24.     while(!Q.empty()){
  25.  
  26.         int u=Q.top().s,ds=Q.top().f;
  27.         Q.pop();
  28.  
  29.         if(dist[u]!=-1)
  30.             continue;
  31.         dist[u]=ds;
  32.         for(int i=0;i<graph[u].size();i++){
  33.             int v=graph[u][i].f,w=graph[u][i].s;
  34.             Q.push(mp(ds+w,v));
  35.         }
  36.     }
  37.     return ;
  38. }
  39.  
  40. int main()
  41. {
  42.     //freopen("input","r",stdin);
  43.     int n,m,i;
  44.     si(n);si(m);
  45.     for(i=0;i<m;i++){
  46.         int u,v,w;
  47.         si(u);si(v);si(w);
  48.         u--;v--;
  49.         graph[u].push_back(mp(v,w));
  50.         graph[v].push_back(mp(u,w));
  51.     }
  52.     dijkstra(0);
  53.     for(i=0;i<n;i++)
  54.         cout<<dist[i]<<" ";
  55.     cout<<endl;
  56.     return 0;
  57. }
  58.  
  59.  
  60. // priority_queue<int,vector<int>,greater<int> > less_val_first;
  61. // priority_queue<int> greater_val_first;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement