这道题显然能看出来是一道
l
c
t
lct
lct的题目
我们只需要维护一下
s
i
z
siz
siz就可以了,每次把他
s
p
l
i
t
split
split一下,然后输出
s
i
z
[
x
]
×
(
s
i
z
[
y
]
−
s
i
z
[
x
]
)
siz[x]\times(siz[y]-siz[x])
siz[x]×(siz[y]−siz[x])就好了
这么水,我切了——china_xyc
显然不可能这么简单啊
果然,这么一写,样例都过不去
我们再考虑一下
我们更新的时候更新的是
s
i
z
[
x
]
=
s
i
z
[
s
o
n
[
x
]
[
0
]
]
+
s
i
z
[
s
o
n
[
x
]
[
1
]
]
+
1
siz[x]=siz[son[x][0]]+siz[son[x][1]]+1
siz[x]=siz[son[x][0]]+siz[son[x][1]]+1
相当于我们只更新了他的两个实儿子,但是他还有很多虚子树我们没有考虑到啊
所以我们用
s
i
z
[
x
]
siz[x]
siz[x]表示整个数的大小,
s
i
z
e
[
x
]
size[x]
size[x]表示这个点的虚子树的大小
那么我们需要在
a
c
c
e
s
s
access
access的时候更新一下——
void access(int x){
for(int y=0;x;y=x,x=fa[x])
splay(x),size[x]+=siz[son[x][1]],size[x]-=siz[y],son[x][1]=y,update(x);
}
然后 l i n k link link的时候不能用 m a k e r o o t makeroot makeroot的方法建边,需要先 s p l i t split split一下让他更新上去然后建边
void link(int x,int y){
split(x,y);
fa[x]=y;
size[y]+=siz[x];
update(y);
}
然后就差不多了
这道题就做完了
代码也不是很长
# include <bits/stdc++.h>
using namespace std;
# define Rep(i,a,b) for(int i=a;i<=b;i++)
# define _Rep(i,a,b) for(int i=a;i>=b;i--)
# define RepG(i,u) for(int i=head[u];~i;i=e[i].next)
# define debug puts("QAQ");
typedef long long ll;
const int N=1e5+5;
const int mod=1e9+7;
const double eps=1e-7;
template <typename T> void read(T &x){
x=0;int f=1;
char c=getchar();
for(;!isdigit(c);c=getchar())if(c=='-')f=-1;
for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+c-'0';
x*=f;
}
int n,q;
int fa[N],son[N][2],siz[N],size[N],st[N];
bool tag[N];
bool isroot(int x){
return son[fa[x]][0]!=x&&son[fa[x]][1]!=x;
}
bool locate(int x){
return son[fa[x]][1]==x;
}
void reverse(int x){
swap(son[x][0],son[x][1]);
tag[x]^=1;
}
void update(int x){
siz[x]=siz[son[x][0]]+size[x]+siz[son[x][1]]+1;
}
void pushdown(int x){
if(tag[x]){
if(son[x][0])reverse(son[x][0]);
if(son[x][1])reverse(son[x][1]);
tag[x]=0;
}
}
void rotate(int x){
int y=fa[x],z=fa[y],side=locate(x);
fa[x]=z;
if(!isroot(y))son[z][son[z][1]==y]=x;
son[y][side]=son[x][side^1];
if(son[x][side^1])fa[son[y][side]]=y;
son[x][side^1]=y,fa[y]=x;
update(y),update(x);
}
void splay(int x){
int y=x,top=0;
st[++top]=y;
while(!isroot(y))y=fa[y],st[++top]=y;
while(top)pushdown(st[top--]);
while(!isroot(x)){
int y=fa[x];
if(!isroot(y))rotate(locate(x)==locate(y)?y:x);
rotate(x);
}
update(x);
}
void access(int x){
for(int y=0;x;y=x,x=fa[x])
splay(x),size[x]+=siz[son[x][1]],size[x]-=siz[y],son[x][1]=y,update(x);
}
void makeroot(int x){
access(x),splay(x);
reverse(x);
}
void split(int x,int y){
makeroot(x);
access(y),splay(y);
}
void link(int x,int y){
split(x,y);
fa[x]=y;
size[y]+=siz[x];
update(y);
}
int main()
{
read(n),read(q);
Rep(i,1,n)siz[i]=1;
while(q--){
char opt[10];
int x,y;
scanf("%s%d%d",opt,&x,&y);
if(opt[0]=='A')link(x,y);
else split(x,y),printf("%lld\n",1ll*siz[x]*(siz[y]-siz[x]));
}
return 0;
}