Advertisement
Abrar_Al_Samit

LCA (SPOJ)

Jul 6th, 2021
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 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 = 1005;
  14. vector<int>g[maxn];
  15. void PlayGround() {
  16.     int N; cin >> N;
  17.     for(int i=1; i<=N; ++i) {
  18.         int m; cin >> m;
  19.         while(m--) {
  20.             int child; cin >> child;
  21.             g[i].push_back(child);
  22.             g[child].push_back(i);
  23.         }
  24.     }
  25.     int l = 15;
  26.     vector<vector<int>>up(N+5, vector<int>(l+1));
  27.     vector<int>tin(N+5), tout(N+5);
  28.     int timer = 0;
  29.     function<void(int,int)> dfs = [&] (int node, int parent) {
  30.         tin[node] = timer++;
  31.  
  32.         up[node][0] = parent;
  33.         for(int i=1; i<=l; ++i)
  34.             up[node][i] = up[up[node][i-1]][i-1];
  35.         for(int child : g[node]) if(child != parent) {
  36.             dfs(child, node);
  37.         }
  38.  
  39.         tout[node] = timer++;
  40.     };
  41.     dfs(1, 1);
  42.     auto isAncestor = [=] (int u, int v) {
  43.         return tin[u] <= tin[v] && tout[u] >= tout[v];
  44.     };
  45.     auto getLCA = [=] (int u, int v) {
  46.         if(isAncestor(u, v)) return u;
  47.         if(isAncestor(v, u)) return v;
  48.         for(int i=l; i>=0; --i) if(!isAncestor(up[u][i], v)) {
  49.             u = up[u][i];
  50.         }
  51.         return up[u][0];
  52.     };
  53.     int q; cin >> q;
  54.     while(q--) {
  55.         int u, v; cin >> u >> v;
  56.         cout << getLCA(u, v) << '\n';
  57.     }
  58.     for(int i=1; i<=N; ++i)
  59.         g[i].clear();
  60.  
  61.     #ifndef ONLINE_JUDGE
  62.         cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
  63.     #endif
  64. }
  65. int main() {
  66.     ios_base::sync_with_stdio(0);
  67.     cin.tie(0);
  68.     cout.tie(0);
  69.     #ifndef ONLINE_JUDGE
  70.         freopen("input.txt", "r", stdin);
  71.     #endif
  72.     int t; cin >> t;
  73.     for(int i=1; i<=t; ++i) {
  74.         cout << "Case " << i << ":\n";
  75.         PlayGround();
  76.     }
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement