Advertisement
Guest User

LCA Err

a guest
Apr 1st, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. const int MAXN=2e5+6;
  6.  
  7. struct node
  8. {
  9.     int val, pos;
  10.     node(int _val=0, int _pos=0) { val=_val; pos=_pos;}
  11. };
  12.  
  13. node t[1000006];
  14.  
  15. int n,T,s;
  16. std::vector<int> E;
  17. std::vector<int> Level;
  18. int P[MAXN];
  19.  
  20. vector<int> a[MAXN];
  21.  
  22. void DFS(int u, int par,int lvl)
  23. {
  24.     E.push_back(u);
  25.     Level.push_back(lvl);
  26.  
  27.     for(int v: a[u])
  28.         if (v!=par)
  29.         {
  30.             DFS(v,u,lvl+1);
  31.             E.push_back(u);
  32.             Level.push_back(lvl);
  33.  
  34.         }
  35. }
  36.  
  37. node Combine(node a, node b)
  38. {
  39.     if (a.val>b.val) return b;
  40.     return a;
  41. }
  42.  
  43. void Build(int id, int l, int r)
  44. {
  45.     if (l==r)
  46.     {
  47.         t[id]=node(Level[l-1],l);
  48.         return;
  49.     }
  50.     int mid=(l+r)>>1;
  51.     Build(id*2,l,mid);
  52.     Build(id*2+1,mid+1,r);
  53.     t[id]=Combine(t[id*2],t[id*2+1]);
  54. }
  55.  
  56. node Query(int id, int l, int r, int L, int R)
  57. {
  58.     if (r<L || R<l) {return node(999999,-1);}
  59.     if (L<=l && r<=R)
  60.     {
  61.         return t[id];
  62.     }
  63.     int mid=(l+r)>>1;
  64.     return Combine(Query(id*2,l,mid,L,R), Query(id*2+1,mid+1,r,L,R));
  65. }
  66.  
  67. int main(int argc, char const *argv[])
  68. {
  69.     // freopen("input.txt","r",stdin);
  70.     cin >>n  >> T;
  71.    
  72.     int u,v;
  73.     for (int i = 2; i <= (n); ++i)
  74.     {
  75.         cin >> u;
  76.         a[u].push_back(i);
  77.     }
  78.  
  79.     DFS(1,1,1);
  80.     for(int i=0; i<(int)E.size(); i++)
  81.     {
  82.         if (!P[E[i]]) P[E[i]]=i+1;
  83.     }
  84.  
  85.     s=E.size();
  86.     Build(1,1,s);
  87.  
  88.     while (T--)
  89.     {
  90.         cin >> u >> v;
  91.         node tmp=Query(1,1,s,min(P[u],P[v]),max(P[u],P[v]));
  92.         cout<<E[tmp.pos-1]<<endl;
  93.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement