Advertisement
Abrar_Al_Samit

Distance In the Tree (Timus)

Jul 7th, 2021
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #include <ext/pb_ds/assoc_container.hpp>
  3. #include <ext/pb_ds/tree_policy.hpp>
  4.  
  5. using namespace std;
  6. using namespace __gnu_pbds;
  7.  
  8.  
  9. #define debug(x) cerr << '[' << (#x) << "] = " << x << '\n';
  10.  
  11. template<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update> ;
  12.  
  13. const int maxn = 50005;
  14. vector<pair<int,int>>g[maxn];
  15. void PlayGround() {
  16.     int N; cin >> N;
  17.     for(int i=1; i<N; ++i) {
  18.         int u, v, w; cin >> u >> v >> w;
  19.         g[u].push_back(make_pair(v, w));
  20.         g[v].push_back(make_pair(u, w));
  21.     }
  22.     int l = 20, timer = 0;
  23.     vector<int>dist(maxn), tin(maxn), tout(maxn);
  24.     vector<vector<int>>up(N+5, vector<int>(l+1));
  25.     function<void(int,int)> DFS = [&] (int node, int parent) {
  26.         tin[node] = timer++;
  27.  
  28.         up[node][0] = parent;
  29.         for(int i=1; i<=l; ++i)
  30.             up[node][i] = up[up[node][i-1]][i-1];
  31.  
  32.         for(auto p : g[node]) if(p.first!=parent) {
  33.             dist[p.first] = dist[node] + p.second;
  34.             DFS(p.first, node);
  35.         }
  36.  
  37.         tout[node] = timer++;
  38.     };
  39.     DFS(1, 1);
  40.  
  41.     auto isAncestor = [=] (int u, int v) {
  42.         return tin[u] <= tin[v] && tout[u] >= tout[v];
  43.     };
  44.     auto getLCA = [=] (int u, int v) {
  45.         if(isAncestor(u, v)) return u;
  46.         if(isAncestor(v, u)) return v;
  47.         for(int i=l; i>=0; --i) if(!isAncestor(up[u][i], v)) {
  48.             u = up[u][i];
  49.         }
  50.         return up[u][0];
  51.     };
  52.     int q; cin >> q;
  53.     while(q--) {
  54.         int u, v; cin >> u >> v;
  55.         cout << dist[u] + dist[v] - 2 * dist[getLCA(u, v)] << '\n';
  56.     }
  57.  
  58.     #ifndef ONLINE_JUDGE
  59.         cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
  60.     #endif
  61. }
  62. int main() {
  63.     ios_base::sync_with_stdio(0);
  64.     cin.tie(0);
  65.     cout.tie(0);
  66.     #ifndef ONLINE_JUDGE
  67.         freopen("input.txt", "r", stdin);
  68.     #endif
  69.     PlayGround();
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement