at3107

Untitled

Sep 25th, 2020 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. // Problem : Shortest Path Revisited
  2. // Contest : HackerEarth - Algorithms - Graphs - Shortest Path Algorithms
  3. // URL : https://www.hackerearth.com/practice/algorithms/graphs/shortest-path-algorithms/practice-problems/algorithm/shortest-path-revisited-9e1091ea/
  4. // Memory Limit : 256 MB
  5. // Time Limit : 3000 ms
  6. // Powered by CP Editor (https://github.com/cpeditor/cpeditor)
  7.  
  8. #include<bits/stdc++.h>
  9. using namespace std;
  10. #define F first
  11. #define S second
  12. #define ll long long
  13.  
  14. int main()
  15. {
  16.     ll n,m,k,hell=1e8,a,b;
  17.     cin>>n>>m>>a>>b>>k;
  18.     vector<pair<ll,ll> > adj[n+1];
  19.     ll dis[n+1][k+1];
  20.     bool vis[n+1][k+1];
  21.     memset(vis,0,sizeof(vis));
  22.     for(int i=0;i<n;i++)
  23.     {
  24.         for(int j=0;j<=k;j++)
  25.         {
  26.             dis[i][j]=hell;
  27.         }
  28.     }
  29.     for(int i=0;i<m;i++)
  30.     {
  31.         ll x,y,z;
  32.         cin>>x>>y>>z;
  33.         adj[x].push_back({y,z});
  34.         adj[y].push_back({x,z});
  35.     }
  36.     for(int i=0;i<=k;i++) dis[a][i]=0;
  37.     priority_queue<pair<int,pair<int,int> > >pq;
  38.     pq.push({0,{a,0}});
  39.     while(!pq.empty())
  40.     {
  41.         auto p=pq.top();
  42.         ll x,y,z;
  43.         x=p.F;
  44.         y=p.S.F;
  45.         z=p.S.S;
  46.         pq.pop();
  47.         if(vis[y][z]==1) continue;
  48.         vis[y][z]=1;
  49.         for(auto i:adj[y])
  50.         {  
  51.             if(dis[i.F][z]>dis[y][z]+i.S)
  52.             {
  53.                 dis[i.F][z]=dis[y][z]+i.S;
  54.                 pq.push({-dis[i.F][z],{i.F,z}});
  55.             }
  56.             if(z<k)
  57.             {
  58.                 if(dis[i.F][z+1]>dis[y][z])
  59.                 {
  60.                     dis[i.F][z+1]=dis[y][z];
  61.                     pq.push({-dis[i.F][z+1],{i.F,z+1}});
  62.                 }
  63.             }
  64.         }
  65.     }
  66.     ll ans=hell;
  67.     for(int i=0;i<=k;i++) ans=min(ans,dis[b][i]);
  68.     if(ans==hell) cout<<-1;
  69.     else cout<<ans;
  70.     return 0;
  71. }
Add Comment
Please, Sign In to add comment