Bzoj3510:首都
Sol
\(LCT\)动态维护树重心
方法一
因为只有加边,所以可以暴力启发式合并,维护重心
维护子树信息,子树大小不超过一半
复杂度两只\(log\)
方法二
扣出两个重心的链,链上二分找
每次\(Splay\)重心,应该是一只\(log\)的吧。。。
# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e5 + 5);
IL int Input(){
RG int x = 0, z = 1; RG char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
}
int n, m, Xor, fa[_], ch[2][_], rev[_], S[_], sum[_], val[_], rt[_];
char op;
IL int Son(RG int x){
return ch[1][fa[x]] == x;
}
IL int Isroot(RG int x){
return ch[0][fa[x]] != x && ch[1][fa[x]] != x;
}
IL void Reverse(RG int x){
if(!x) return;
rev[x] ^= 1, swap(ch[0][x], ch[1][x]);
}
IL void Pushdown(RG int x){
if(!rev[x]) return;
Reverse(ch[0][x]), Reverse(ch[1][x]), rev[x] ^= 1;
}
IL void Update(RG int x){
sum[x] = sum[ch[0][x]] + sum[ch[1][x]] + val[x] + 1;
}
IL void Rotate(RG int x){
RG int y = fa[x], z = fa[y], c = Son(x);
if(!Isroot(y)) ch[Son(y)][z] = x; fa[x] = z;
ch[c][y] = ch[!c][x], fa[ch[c][y]] = y;
ch[!c][x] = y, fa[y] = x, Update(y);
}
IL void Splay(RG int x){
S[S[0] = 1] = x;
for(RG int y = x; !Isroot(y); y = fa[y]) S[++S[0]] = fa[y];
while(S[0]) Pushdown(S[S[0]--]);
for(RG int y = fa[x]; !Isroot(x); Rotate(x), y = fa[x])
if(!Isroot(y)) Son(x) ^ Son(y) ? Rotate(x) : Rotate(y);
Update(x);
}
IL void Access(RG int x){
for(RG int y = 0; x; y = x, x = fa[x]){
Splay(x), val[x] += sum[ch[1][x]] - sum[y];
ch[1][x] = y, Update(x);
}
}
IL void Makeroot(RG int x){
Access(x), Splay(x), Reverse(x);
}
IL void Split(RG int x, RG int y){
Makeroot(x), Access(y), Splay(y);
}
IL void Adjust(RG int x, RG int y){
Split(x, y);
RG int flg = 0, t = y, g = 0, size = sum[y] >> 1, sl = 0, sr = 0;
while(t){
Pushdown(t);
RG int ls = ch[0][t], rs = ch[1][t], ssl = sum[ls] + sl, ssr = sum[rs] + sr;
if(ssl <= size && ssr <= size){
if(!flg || t < g) g = t, flg = 1;
if(ssl == ssr) break;
}
if(ssr > ssl) sl += sum[ls] + val[t] + 1, t = rs;
else sr += sum[rs] + val[t] + 1, t = ls;
}
Splay(g);
Xor ^= x ^ y ^ g, rt[x] = rt[y] = rt[g] = g;
}
IL int Findrt(RG int x){
return x == rt[x] ? x : rt[x] = Findrt(rt[x]);
}
IL void Link(RG int x, RG int y){
Makeroot(x), Makeroot(y);
fa[x] = y, val[y] += sum[x], Update(y);
Adjust(Findrt(x), Findrt(y));
}
int main(RG int argc, RG char *argv[]){
n = Input(), m = Input();
for(RG int i = 1; i <= n; ++i) rt[i] = i, Xor ^= i, sum[i] = 1;
for(RG int i = 1, x, y; i <= m; ++i){
scanf(" %c", &op);
if(op == 'A') x = Input(), y = Input(), Link(x, y);
else if(op == 'Q') x = Input(), printf("%d\n", Findrt(x));
else scanf(" %*s"), printf("%d\n", Xor);
}
return 0;
}