Advertisement
Anikdip

Untitled

Oct 21st, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef pair<int,int> ii;
  6. typedef vector<int> vi;
  7.  
  8. #define mp make_pair
  9. #define pb push_back
  10.  
  11. vi adj[100001];
  12. vi cost[100001];
  13. int dis[100001],n;
  14. int path[100001];
  15.  
  16. int dijkastra(int source , int destination )
  17. {
  18.     priority_queue< ii, vector <ii> ,greater<ii> > pq;
  19.  
  20.     for(int i = 1; i<=n; i++)
  21.         dis[i] = INT_MAX;
  22.  
  23.     dis[source] = 0;
  24.  
  25.     pq.push(mp(0,source));
  26.  
  27.     while(!pq.empty())
  28.     {
  29.         ii temp = pq.top();
  30.         pq.pop();
  31.  
  32.  
  33.         int u = temp.second;
  34.         if(u == destination)
  35.             return dis[u];
  36.         for(int i = 0; i<adj[u].size(); i++)
  37.         {
  38.             int v = adj[u][i];
  39.             int c = cost[u][i];
  40.  
  41.             if(dis[u]+c < dis[v])
  42.             {
  43.                 dis[v] = dis[u] + c;
  44.  
  45.                 path[v] = u;
  46.  
  47.                 pq.push(mp(dis[v],v));
  48.             }
  49.  
  50.         }
  51.  
  52.  
  53.     }
  54.  
  55.    return dis[destination];
  56. }
  57. void print_path(int des)
  58. {
  59.     if(path[des]==-1)
  60.     {
  61.         cout<<des<<' ';
  62.         return;
  63.     }
  64.     print_path(path[des]);
  65.     cout<<des<<' ';
  66. }
  67. int main()
  68.  
  69. {
  70.     int  adge,a,b,w;
  71.      cin>>n>>adge;
  72.  
  73.      while(adge--)
  74.      {
  75.          cin>>a>>b>>w;
  76.           adj[a].pb(b);
  77.           adj[b].pb(a);
  78.           cost[a].pb(w);
  79.           cost[b].pb(w);
  80.      }
  81.  
  82.      dijkastra(1,n);
  83.  
  84.      if(dijkastra(1,n)!= INT_MAX)
  85.      {
  86.  
  87.          path[1]=-1;
  88.          print_path(n);
  89.      }
  90.      else
  91.         cout<<-1<<endl;
  92.  
  93.      return 0;
  94.  
  95.  
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement