Advertisement
Rentib

Untitled

Feb 5th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<pair<int, int>> G[500007];
  4. int up[500007][19], maks[500007][19];
  5. int pre[500007], pos[500007], pr, po;
  6. void DFS(int a, int vater){
  7.   pre[a] = ++pr;
  8.   up[a][0] = vater;
  9.   for(int i = 1;i < 19;i++){
  10.     up[a][i] = up[up[a][i - 1]][i - 1];
  11.     maks[a][i] = max(maks[a][i - 1], maks[up[a][i - 1]][i - 1]);
  12.   }
  13.   for(auto i : G[a])
  14.     if(i.first != vater){
  15.       maks[i.first][0] = i.second;
  16.       DFS(i.first, a);
  17.     }
  18.   pos[a] = ++po;
  19. }
  20. bool ancestor(int u, int v){
  21.   return pre[u] <= pre[v] && pos[u] >= pos[v];
  22. }
  23. int LCA(int u, int v){
  24.   if(ancestor(u, v))
  25.     return u;
  26.   if(ancestor(v, u))
  27.     return v;
  28.   for(int i = 18;i >= 0;i--)
  29.     if(ancestor(up[u][i], v))
  30.       u = up[u][i];
  31.   return up[u][0];
  32. }
  33. int Maks(int a, int k){
  34.   int m = -INT_MAX;
  35.   for(int i = 18;i >= 0;i--){
  36.     if(!ancestor(k, up[a][i]))
  37.       continue;
  38.     m = max(m, maks[a][i]);
  39.     a = up[a][i];
  40.   }
  41.   return m;
  42. }
  43. int main(){
  44.   ios_base::sync_with_stdio(0);
  45.   cin.tie(0);
  46.   cout.tie(0);
  47.   int n, a, b;
  48.   cin >> n;
  49.   for(int i = 1, c;i < n;i++){
  50.     cin >> a >> b >> c;
  51.     G[a].emplace_back(b, c);
  52.     G[b].emplace_back(a, c);
  53.   }
  54.   DFS(1, 1);
  55.   while(cin >> a){
  56.     if(a == -1)
  57.       break;
  58.     cin >> b;
  59.     if(a == b){
  60.       cout << 0;
  61.       continue;
  62.     }
  63.     int k = LCA(a, b);
  64.     cout << max(Maks(a, k), Maks(b, k)) << '\n';
  65.   }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement