Advertisement
akashtadwai

Dijkstra-DP atmost K zeroing weights

Aug 22nd, 2021
2,092
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define ar array<int,3>
  4. int main(){
  5.     int n,m,k;
  6.     cin>>n>>m>>k;
  7.     vector<vector<pair<int, int>>> adj(n);
  8.     for(int i=0;i<m;i++){
  9.         int u, v, w;
  10.         cin>>u>>v>>w;
  11.         adj[u-1].push_back({v-1, w});
  12.         adj[v-1].push_back({u-1, w});
  13.     }
  14.     vector<vector<int>> dp(n, vector<int>(k + 1, INT_MAX)); //dp[i][j] -> 0 to i with atmost j skips
  15. priority_queue<ar, vector<ar>, greater<ar>> q; // {dist,node,used}
  16.         q.push({0, 0, 0});
  17.         dp[0][0] = 0 ;
  18.         while(!q.empty()){
  19.             auto [d,n,next] = q.top();
  20.             q.pop();
  21.             if(d!=dp[n][next]) continue;
  22.             if(n==0) dp[n][next]=0;
  23.             for(auto [v,w]:adj[n]){
  24.                 if(dp[n][next]+w<dp[v][next]){
  25.                     dp[v][next] = dp[n][next]+w;
  26.                     q.push({dp[v][next],v,next});
  27.                 }
  28.                 if(next == k) continue;
  29.                 if(dp[n][next]<dp[v][next+1]){
  30.                     dp[v][next+1] = dp[n][next];
  31.                     q.push({dp[v][next+1],v,next+1});
  32.                 }
  33.             }
  34.         }
  35.     for(int i = 0;i < n;i++){
  36.         cout<<dp[i][k]<<" ";
  37.     }
  38.     cout<<endl;
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement