Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Problem : Shortest Path Revisited
- // Contest : HackerEarth - Algorithms - Graphs - Shortest Path Algorithms
- // URL : https://www.hackerearth.com/practice/algorithms/graphs/shortest-path-algorithms/practice-problems/algorithm/shortest-path-revisited-9e1091ea/
- // Memory Limit : 256 MB
- // Time Limit : 3000 ms
- // Powered by CP Editor (https://github.com/cpeditor/cpeditor)
- #include<bits/stdc++.h>
- using namespace std;
- #define F first
- #define S second
- #define ll long long
- int main()
- {
- ll n,m,k,hell=1e8,a,b;
- cin>>n>>m>>a>>b>>k;
- vector<pair<ll,ll> > adj[n+1];
- ll dis[n+1][k+1];
- bool vis[n+1][k+1];
- memset(vis,0,sizeof(vis));
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<=k;j++)
- {
- dis[i][j]=hell;
- }
- }
- for(int i=0;i<m;i++)
- {
- ll x,y,z;
- cin>>x>>y>>z;
- adj[x].push_back({y,z});
- adj[y].push_back({x,z});
- }
- for(int i=0;i<=k;i++) dis[a][i]=0;
- priority_queue<pair<int,pair<int,int> > >pq;
- pq.push({0,{a,0}});
- while(!pq.empty())
- {
- auto p=pq.top();
- ll x,y,z;
- x=p.F;
- y=p.S.F;
- z=p.S.S;
- pq.pop();
- if(vis[y][z]==1) continue;
- vis[y][z]=1;
- for(auto i:adj[y])
- {
- if(dis[i.F][z]>dis[y][z]+i.S)
- {
- dis[i.F][z]=dis[y][z]+i.S;
- pq.push({-dis[i.F][z],{i.F,z}});
- }
- if(z<k)
- {
- if(dis[i.F][z+1]>dis[y][z])
- {
- dis[i.F][z+1]=dis[y][z];
- pq.push({-dis[i.F][z+1],{i.F,z+1}});
- }
- }
- }
- }
- ll ans=hell;
- for(int i=0;i<=k;i++) ans=min(ans,dis[b][i]);
- if(ans==hell) cout<<-1;
- else cout<<ans;
- return 0;
- }
Add Comment
Please, Sign In to add comment