1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
| #include<bits/stdc++.h> #define Inf 0x3f3f3f3f using namespace std; typedef long long LL; typedef pair<int,int> P; const int MAXX=100005;
struct LCT{ struct node{ int fa,left,right,val,sum,lazy; }s[MAXX]; inline void pushup(int i){ s[i].sum=s[s[i].left].sum^s[s[i].right].sum^s[i].val; } inline void pushdown(int i){ if(s[i].lazy){ swap(s[i].left,s[i].right); if(s[i].left) s[s[i].left].lazy^=1; if(s[i].right) s[s[i].right].lazy^=1; s[i].lazy=0; } } inline int identify(int i){ if(s[s[i].fa].left==i) return 0; if(s[s[i].fa].right==i) return 1; return -1; } inline void connect(int i,int f,int op){ s[i].fa=f; if(op==1) s[f].right=i; if(op==0) s[f].left=i; } inline void rotate(int x){ int y=s[x].fa; int z=s[y].fa; int opy=identify(y); int opx=identify(x); int u=0; if(opx==1) u=s[x].left; if(opx==0) u=s[x].right; connect(u,y,opx); connect(y,x,opx^1); connect(x,z,opy); pushup(y); pushup(x); } void pushall(int x){ if(identify(x)!=-1) pushall(s[x].fa); pushdown(x); } inline void splay(int i){ pushall(i); while(identify(i)!=-1){ int up=s[i].fa; if(identify(up)==-1) rotate(i); else if(identify(i)==identify(up)) rotate(up),rotate(i); else rotate(i),rotate(i); } } inline int access(int k){ int temp=0; while(k){ splay(k); s[k].right=temp; pushup(k); temp=k; k=s[k].fa; } return temp; } inline void makeroot(int k){ access(k); splay(k); swap(s[k].left,s[k].right); if(s[k].left) s[s[k].left].lazy^=1; if(s[k].right) s[s[k].right].lazy^=1; } inline int findroot(int k){ access(k); splay(k); while(s[k].left){ pushdown(k); k=s[k].left; } splay(k); return k; } inline void split(int x,int y){ makeroot(x); access(y); splay(y); } inline int lca(int x,int y){ access(x); return access(y); } inline int lca(int r,int x,int y){ makeroot(r); access(x); return access(y); } inline bool link(int x,int y){ makeroot(x); if(findroot(y)==x) return false; s[x].fa=y; return true; } inline bool cut(int x,int y){ if(findroot(x)!=findroot(y)) return false; split(x,y); if(s[x].fa!=y||s[x].right) return false; s[x].fa=s[y].left=0; pushup(x); return true; } }lct;
int n,m;
inline void solve(){ scanf("%d",&n); for(int i=1;i<n;++i){ int jj,kk; scanf("%d%d",&jj,&kk); lct.link(jj,kk); }
scanf("%d",&m); while(m--){ int r,x,y; scanf("%d%d%d",&r,&x,&y); printf("%d\n",lct.lca(r,x,y)); } }
signed main(){
solve(); return 0; }
|