MAGCARI

Hospital

May 8th, 2023
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.07 KB | None | 0 0
  1. /*
  2.     Task    :
  3.     Author  : Phumipat C. [MAGCARI]
  4.     Language: C++
  5.     Created : 03 May 2023 [18:53]
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. int dp[100010]; // dp[i] = minimum distance from i to hospital node in subtree
  10. vector<pair<int ,int > > g[100010];
  11. pair<int ,int > p[100010];
  12. void dfs(int now,int par){
  13.     for(auto x:g[now]){
  14.         if(x.first == par)  continue;
  15.         p[x.first] = {now,x.second};
  16.         dfs(x.first, now);
  17.     }
  18. }
  19. int main(){
  20.     int n,m,s,q;
  21.     cin >> n >> m >> s >> q;
  22.     for(int i=1;i<n;i++){
  23.         int u,v,w;
  24.         cin >> u >> v >> w;
  25.         g[u].push_back({v,w});
  26.         g[v].push_back({u,w});
  27.     }
  28.     dfs(s,0);
  29.     for(int i=1;i<=n;i++)
  30.         dp[i] = 1e9;
  31.     dp[s] = 0;
  32.     while(q--){
  33.         int opr,u;
  34.         cin >> opr >> u;
  35.         if(opr == 0){
  36.             dp[u] = 0;
  37.             int pathWeightFromStart = 0;
  38.             while(u != s){
  39.                 dp[u] = min(dp[u],pathWeightFromStart);
  40.                 pathWeightFromStart += p[u].second;
  41.                 u = p[u].first;
  42.             }
  43.         }else{
  44.             int ans = dp[u],pathWeightFromStart = 0;
  45.             while(u != s){
  46.                 ans = min(ans,pathWeightFromStart + dp[u]);
  47.                 pathWeightFromStart+=p[u].second;
  48.                 u = p[u].first;
  49.             }
  50.             cout << ans << '\n';
  51.         }
  52.     }
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment