您的位置:首页 > 运维架构

LCT维护子树信息(BZOJ4530:[BJOI2014]大融合)

2018-01-22 15:36 429 查看

题面

没有权限号的可以去LOJ

Sol

大家都知道,\(LCT\)上有许多实边和虚边

实边就是每棵\(Splay\)上的既认父亲又认儿子的边

虚边就是\(Splay\)和\(Splay\)之间只认父亲的的边

那么每个点就有它的虚儿子和实儿子,实际上虚儿子才是它在\(LCT\)维护的树上的真正的儿子

当你\(Access(x)\)时,\(x\)的虚儿子加上它自己就是它子树的信息

所以我们要维护每个点虚儿子的信息和LCT子树的信息(也就是虚儿子+实儿子+自己)

怎么维护?

你会发现这只会在\(Access\)和\(Link\)操作中改变

\(Access\)时,这个点的实儿子和虚儿子会有改变,那么维护的虚儿子的信息就减去原来的加上现在的就好了

\(Link\)时,这个点多了一个虚儿子,直接加上就好,但是这个点的祖先都要更改,不好操作,直接把它也\(Makeroot\)就好

LCT子树的信息可以直接写在\(Update\)内

然后这个题就是水题了

询问就是两边\(size\)的乘积

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define ls ch[0][x]
# define rs ch[1][x]
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e5 + 10);

IL ll Read(){
RG char c = getchar(); RG ll x = 0, z = 1;
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, Q, ch[2][_], fa[_], size[_], sum[_], rev[_], S[_];

IL bool Son(RG int x){  return ch[1][fa[x]] == x;  }

IL bool Isroot(RG int x){  return ch[0][fa[x]] != x && ch[1][fa[x]] != x;  }

IL void Reverse(RG int x){  if(!x) return; swap(ls, rs); rev[x] ^= 1;  }

IL void Update(RG int x){  sum[x] = sum[ls] + sum[rs] + size[x] + 1;  }

IL void Pushdown(RG int x){  if(!rev[x]) return; Reverse(ls); Reverse(rs); rev[x] = 0;  }

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), size[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 Link(RG int x, RG int y){  Makeroot(x); Makeroot(y); fa[x] = y; size[y] += sum[x]; Update(y);  }

IL void Split(RG int x, RG int y){  Makeroot(x); Access(y); Splay(y);  }

int main(RG int argc, RG char* argv[]){
n = Read(); Q = Read();
while(Q--){
RG char op; scanf(" %c", &op); RG int x = Read(), y = Read();
if(op == 'A') Link(x, y);
else Split(x, y), printf("%lld\n", 1LL * sum[x] * (sum[y] - sum[x]));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: