Advertisement
a_pramanik

Dijkstra fast

Nov 30th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. //-_-
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. #define pb push_back
  6. #define ll long long int
  7. #define inf 100000000000001
  8. #define pi (2.0*acos(0.0))
  9. #define vsort(v)   sort(v.begin(),v.end())
  10. #define ull unsigned long long int
  11. #define mem(a, b) memset(a, b, sizeof a)
  12. #define cf 100009
  13.  
  14. struct node
  15. {
  16.     ll nd, cst;
  17.  
  18.     node(ll x, ll y)
  19.     {
  20.         nd = x;
  21.         cst = y;
  22.     }
  23.  
  24.  
  25. };
  26.  
  27. bool operator < (node a, node b)
  28. {
  29.     return a.cst>b.cst;
  30. }
  31.  
  32.  
  33. vector<ll>a[cf], cost[cf];
  34. priority_queue<node>q;
  35. ll dis[cf], par[cf];
  36.  
  37. int main()
  38. {
  39.     ll n, m, i, j, k, x, y, c;
  40.  
  41.     while(scanf("%lld%lld", &n, &m)==2){
  42.  
  43.         for(i=1; i<=m; i++)
  44.         {
  45.             scanf("%lld%lld%lld", &x, &y, &c);
  46.             a[x].pb(y);
  47.             a[y].pb(x);
  48.             cost[x].pb(c);
  49.             cost[y].pb(c);
  50.         }
  51.  
  52.         for(i=0; i<=n; i++){
  53.             dis[i]=inf;
  54.             par[i]=-1;
  55.         }
  56.  
  57.         q.push(node(1, 0));
  58.         dis[1]=0;
  59.  
  60.         while(!q.empty())
  61.         {
  62.             node top = q.top();
  63.             q.pop();
  64.             x = top.nd;
  65.             for(i=0; i<a[x].size(); i++)
  66.             {
  67.                 y = a[x][i];
  68.                 c = cost[x][i];
  69.  
  70.                 if(dis[y]>dis[x]+c)
  71.                 {
  72.                     par[y]=x;
  73.                     dis[y]=dis[x]+c;
  74.                     q.push(node(y, dis[y]));
  75.                 }
  76.             }
  77.         }
  78.  
  79.         if(dis[n]==inf)printf("-1\n");
  80.         else{
  81.                 vector<ll>ans;
  82.                 //printf("bal\n");
  83.                 i = n;
  84.                 while(1){
  85.                         ans.pb(i);
  86.                     if(par[i]==-1)break;
  87.                     i = par[i];
  88.                 }
  89.                 for(i=ans.size()-1; i>=0; i--)printf("%lld ", ans[i]);
  90.                 printf("\n");
  91.                 ans.clear();
  92.         }
  93.  
  94.  
  95.         for(i=1; i<=n; i++){
  96.             a[i].clear();
  97.             cost[i].clear();
  98.         }
  99.  
  100.  
  101.     }
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement