Advertisement
a_pramanik

dijkstra sakib

Jan 18th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. ///Problem: http://codeforces.com/problemset/problem/20/C
  2. #include<bits/stdc++.h>
  3. #define inf 1000000000000
  4. #define ll long long
  5. using namespace std;
  6. int n,vis[100005],par[100005];
  7. ll dist[100005];
  8. vector<int>adj[100005];
  9. vector<ll>cost[100005];
  10. struct node
  11. {
  12.     int u;
  13.     ll w;
  14.     node(int x,ll z)
  15.     {
  16.         u=x;
  17.         w=z;
  18.     }
  19. };
  20. bool operator <(node a,node b)
  21. {
  22.     return a.w>b.w;
  23. }
  24. priority_queue<node>pq;
  25. stack<int>s;
  26. void dijkstra()
  27. {
  28.     int i;
  29.     for(i=2;i<=n;i++)
  30.         dist[i]=inf,par[i]=i;
  31.  
  32.     pq.push(node(1,0));
  33.     while(!pq.empty())
  34.     {
  35.         node x=pq.top();
  36.         pq.pop();
  37.         if(x.w!=dist[x.u])
  38.             continue;
  39.         for(i=0;i<adj[x.u].size();i++)
  40.         {
  41.             int y=adj[x.u][i];
  42.             if(dist[y]>dist[x.u]+cost[x.u][i])
  43.                 dist[y]=dist[x.u]+cost[x.u][i],pq.push(node(y,dist[y])),par[y]=x.u;
  44.         }
  45.     }
  46. }
  47. int main()
  48. {
  49.     int i,m,x,y;
  50.     ll z;
  51.  
  52.     scanf("%d%d",&n,&m);
  53.     while(m--)
  54.     {
  55.         scanf("%d%d%lld",&x,&y,&z);
  56.         adj[x].push_back(y);
  57.         adj[y].push_back(x);
  58.         cost[x].push_back(z);
  59.         cost[y].push_back(z);
  60.     }
  61.  
  62.     dijkstra();
  63.  
  64.     if(dist[n]==inf)
  65.         printf("-1\n");
  66.     else
  67.     {
  68.         par[1]=-1;
  69.         x=n;
  70.         while(x!=-1)
  71.         {
  72.             s.push(x);
  73.             x=par[x];
  74.         }
  75.         while(!s.empty())
  76.             printf("%d ",s.top()),s.pop();
  77.         cout<<endl;
  78.     }
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement