Advertisement
cjchirag7

Shortest Path Revisited | Hackerearth

Aug 20th, 2020
458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int long long
  3.  
  4. const int INF=1e18;
  5. using namespace std;
  6.  
  7. struct st{
  8. int node;
  9. int offers;
  10. int d;
  11. };
  12.  
  13. struct comp
  14. {
  15.     bool operator () (st s1, st s2)
  16.     {
  17.         return s1.d > s2.d;
  18.     }
  19. };
  20.  
  21. int32_t main()
  22. {
  23.     ios_base::sync_with_stdio(false);
  24.     cin.tie(NULL);
  25.     cout.tie(NULL);
  26.  
  27.     int n,m,k;
  28.     cin>>n>>m>>k;
  29.  
  30.     vector<vector<pair<int,int> > > adj(n);
  31.  
  32.     for(int i=0; i<m; i++)
  33.     {
  34.         int u,v,w;
  35.         cin>>u>>v>>w;
  36.         u--;
  37.         v--;
  38.         adj[u].push_back({v,w});
  39.         adj[v].push_back({u,w});        
  40.     }
  41.  
  42.     vector<vector<int> > dist(n,vector<int>(k+1,INF));
  43.  
  44.     priority_queue<st,vector<st> , comp> pq;
  45.  
  46.     pq.push({0,k,0}) ;
  47.  
  48.     dist[0][k]=0;
  49.  
  50.     while(!pq.empty())
  51.     {
  52.         st t=pq.top();
  53.         int d=t.d;
  54.         int node=t.node;
  55.         int offers=t.offers;
  56.         pq.pop();
  57.         if(d>dist[node][offers])
  58.             continue;
  59.         for(auto it: adj[node])
  60.         {
  61.             int v=it.first;
  62.             int temp=it.second;
  63.             if(offers>0)
  64.             {
  65.                 if(dist[v][offers-1]>d)
  66.                      {
  67.                          dist[v][offers-1]=d;
  68.                          pq.push({v,offers-1,d});  
  69.                      }
  70.             }
  71.             if(dist[v][offers]>d+temp)
  72.             {
  73.                          dist[v][offers]=d+temp;            
  74.                          pq.push({v,offers,d+temp});            
  75.             }
  76.         }
  77.     }
  78.     for(int i=0; i<n; i++)
  79.     {
  80.         cout<<*min_element(dist[i].begin(),dist[i].end())<<" ";
  81.     }
  82.     cout<<'\n';
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement