Advertisement
Guest User

Untitled

a guest
Mar 29th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main() {
  6. freopen("ancestor.in","r",stdin);
  7. freopen("ancestor.out","w",stdout);
  8. int n;
  9. cin>>n;
  10. vector <vector<int>> g(n);
  11. int root=0;
  12. for (int i=0;i<n;i++) {
  13. int x; cin>>x; x--; if (x==-1) root=i; else {g[i].push_back(x); g[x].push_back(i); }
  14. }
  15. vector <bool> used(n);
  16. vector <int> dist(n);
  17. vector <int> parent(n);
  18. used[root]=true;
  19. dist[root]=true;
  20. queue <int> q;
  21. q.push(root);
  22. while (!q.empty()) {
  23. int c=q.front(); q.pop();
  24. for (int i=0;i<g[c].size();i++) {
  25. 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; }
  26. }
  27. }
  28.  
  29. int q1;
  30. cin>>q1;
  31. int binup[n][30];
  32. for (int i=0;i<30;i++) {
  33. 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];
  34. }
  35.  
  36. for (int i=0;i<q1;i++) {
  37. int p1,p2; cin>>p1>>p2; p1--; p2--;
  38. int t=dist[p2]-dist[p1];
  39. int cur=0;
  40. if (t<0) cout<<"0\n"; else {
  41. while (t!=0) {
  42. if (t%2) {
  43. p2=binup[p2][cur];
  44. }
  45. cur++; t/=2;
  46. }
  47. if (p1==p2) cout<<"1\n"; else cout<<"0\n";
  48. }
  49.  
  50. }
  51. return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement