Link Cut Tree
刚开始写了个指针版。。调了一天然后放弃了。。
最后还是学了黄学长的板子!!#include#define INF 0x3f3f3f3f#define full(a, b) memset(a, b, sizeof a)using namespace std;typedef long long ll;inline int lowbit(int x){ return x & (-x); }inline int read(){ int X = 0, w = 0; char ch = 0; while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); } while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar(); return w ? -X : X;}inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }inline int lcm(int a, int b){ return a / gcd(a, b) * b; }template inline T max(T x, T y, T z){ return max(max(x, y), z); }template inline T min(T x, T y, T z){ return min(min(x, y), z); }template inline A fpow(A x, B p, C lyd){ A ans = 1; for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd; return ans;}const int N = 300005;int ch[N][2], val[N], sum[N], rev[N], tot, fa[N], st[N], n, m;void newNode(int v){ val[++tot] = v, sum[tot] = v; rev[tot] = ch[tot][0] = ch[tot][1] = fa[tot] = 0;}void reverse(int x){ swap(ch[x][0], ch[x][1]); rev[x] ^= 1;}void push_up(int x){ sum[x] = val[x] ^ sum[ch[x][0]] ^ sum[ch[x][1]];}void push_down(int x){ if(rev[x]){ reverse(ch[x][0]), reverse(ch[x][1]); //rev[x] ^= 1, rev[ch[x][0]] ^= 1, rev[ch[x][1]] ^= 1; //swap(ch[x][0], ch[x][1]); rev[x] ^= 1; }}bool isRoot(int x){ return (!fa[x] || (ch[fa[x]][0] != x && ch[fa[x]][1] != x));}void rotate(int x){ int y = fa[x], z = fa[y], p = (ch[y][1] == x)^1; ch[y][p^1] = ch[x][p], fa[ch[x][p]] = y; if(!isRoot(y)) ch[z][ch[z][1] == y] = x; fa[x] = z, ch[x][p] = y, fa[y] = x; push_up(y), push_up(x);}void splay(int x){ int pos = 0; st[++pos] = x; for(int i = x; !isRoot(i); i = fa[i]) st[++pos] = fa[i]; while(pos) push_down(st[pos --]); while(!isRoot(x)){ int y = fa[x], z = fa[y]; if(!isRoot(y)){ if((ch[y][1] == x) ^ (ch[z][1] == y)) rotate(x); else rotate(y); } rotate(x); }}void access(int x){ for(int p = 0; x; p = x, x = fa[x]) splay(x), ch[x][1] = p, push_up(x);}void makeRoot(int x){ access(x), splay(x), reverse(x);}int findRoot(int x){ access(x), splay(x); while(ch[x][0]) push_down(x), x = ch[x][0]; splay(x); return x;}void split(int x, int y){ makeRoot(x), access(y), splay(y);}void link(int x, int y){ makeRoot(x); if(findRoot(y) == x) return; fa[x] = y; push_up(y);}void cut(int x, int y){ makeRoot(x); if(findRoot(y) != x || fa[y] != x || ch[y][0]) return; ch[x][1] = fa[y] = 0; push_up(x);}int main(){ n = read(), m = read(); for(int i = 1; i <= n; i ++){ int v = read(); newNode(v); } while(m --){ int opt = read(), x = read(), y = read(); if(opt == 0){ split(x, y); printf("%d\n", sum[y]); } else if(opt == 1){ link(x, y); } else if(opt == 2){ cut(x, y); } else if(opt == 3){ splay(x); val[x] = y; } } return 0;}