Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- const int MAXN=2e5+6;
- struct node
- {
- int val, pos;
- node(int _val=0, int _pos=0) { val=_val; pos=_pos;}
- };
- node t[1000006];
- int n,T,s;
- std::vector<int> E;
- std::vector<int> Level;
- int P[MAXN];
- vector<int> a[MAXN];
- void DFS(int u, int par,int lvl)
- {
- E.push_back(u);
- Level.push_back(lvl);
- for(int v: a[u])
- if (v!=par)
- {
- DFS(v,u,lvl+1);
- E.push_back(u);
- Level.push_back(lvl);
- }
- }
- node Combine(node a, node b)
- {
- if (a.val>b.val) return b;
- return a;
- }
- void Build(int id, int l, int r)
- {
- if (l==r)
- {
- t[id]=node(Level[l-1],l);
- return;
- }
- int mid=(l+r)>>1;
- Build(id*2,l,mid);
- Build(id*2+1,mid+1,r);
- t[id]=Combine(t[id*2],t[id*2+1]);
- }
- node Query(int id, int l, int r, int L, int R)
- {
- if (r<L || R<l) {return node(999999,-1);}
- if (L<=l && r<=R)
- {
- return t[id];
- }
- int mid=(l+r)>>1;
- return Combine(Query(id*2,l,mid,L,R), Query(id*2+1,mid+1,r,L,R));
- }
- int main(int argc, char const *argv[])
- {
- // freopen("input.txt","r",stdin);
- cin >>n >> T;
- int u,v;
- for (int i = 2; i <= (n); ++i)
- {
- cin >> u;
- a[u].push_back(i);
- }
- DFS(1,1,1);
- for(int i=0; i<(int)E.size(); i++)
- {
- if (!P[E[i]]) P[E[i]]=i+1;
- }
- s=E.size();
- Build(1,1,s);
- while (T--)
- {
- cin >> u >> v;
- node tmp=Query(1,1,s,min(P[u],P[v]),max(P[u],P[v]));
- cout<<E[tmp.pos-1]<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement