Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int main() {
- freopen("ancestor.in","r",stdin);
- freopen("ancestor.out","w",stdout);
- int n;
- cin>>n;
- vector <vector<int>> g(n);
- int root=0;
- for (int i=0;i<n;i++) {
- int x; cin>>x; x--; if (x==-1) root=i; else {g[i].push_back(x); g[x].push_back(i); }
- }
- vector <bool> used(n);
- vector <int> dist(n);
- vector <int> parent(n);
- used[root]=true;
- dist[root]=true;
- queue <int> q;
- q.push(root);
- while (!q.empty()) {
- int c=q.front(); q.pop();
- for (int i=0;i<g[c].size();i++) {
- if (!used[g[c][i]]) {used[g[c][i]]=true; q.push(g[c][i]); dist[g[c][i]]=dist[c]+1; parent[g[c][i]]=c; }
- }
- }
- int q1;
- cin>>q1;
- int binup[n][30];
- for (int i=0;i<30;i++) {
- for (int j=0;j<n;j++) if (i==0) binup[j][i]=parent[j]; else binup[j][i]=binup[binup[j][i-1]][i-1];
- }
- for (int i=0;i<q1;i++) {
- int p1,p2; cin>>p1>>p2; p1--; p2--;
- int t=dist[p2]-dist[p1];
- int cur=0;
- if (t<0) cout<<"0\n"; else {
- while (t!=0) {
- if (t%2) {
- p2=binup[p2][cur];
- }
- cur++; t/=2;
- }
- if (p1==p2) cout<<"1\n"; else cout<<"0\n";
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement