原题链接:https://www.lydsy.com/JudgeOnline/problem.php?id=4530
大融合
Description
小强要在N个孤立的星球上建立起一套通信系统。这套通信系统就是连接N个点的一个树。
这个树的边是一条一条添加上去的。在某个时刻,一条边的负载就是它所在的当前能够联通的树上路过它的简单路径的数量。
例如,在上图中,现在一共有了5条边。其中,(3,8)这条边的负载是6,因为有六条简单路径2-3-8,2-3-8-7,3-8,3-8-7,4-3-8,4-3-8-7路过了(3,8)。
现在,你的任务就是随着边的添加,动态的回答小强对于某些边的负载的
询问。
Input
第一行包含两个整数N,Q,表示星球的数量和操作的数量。星球从1开始编号。
接下来的Q行,每行是如下两种格式之一:
A x y 表示在x和y之间连一条边。保证之前x和y是不联通的。
Q x y 表示询问(x,y)这条边上的负载。保证x和y之间有一条边。
1≤N,Q≤100000
Output
对每个查询操作,输出被查询的边的负载。
Sample Input
8 6
A 2 3
A 3 4
A 3 8
A 8 7
A 6 5
Q 3 8
Sample Output
6
题解
这算是 L C T \mathcal{LCT} LCT维护虚子树信息的入门题吧,学会了就觉得很简单,主要是网上的大佬数组名诡异至极,不知道表示什么。。。
首先,比较显然的是,询问的答案其实是路径两端点的点数的乘积。考虑如何维护这个答案,我们发现,当 s p l i t ( x , y ) split(x,y) split(x,y)后,此时 s p l a y \mathcal{splay} splay中只有 x , y x,y x,y,那么这两端点的虚子树的大小实际上就是这条边连接的点的数量-1(因为没有算 x , y x,y x,y本身)。
如何求出虚子树大小呢?我们需要维护两个信息:整棵子树的大小
t
o
t
[
v
]
tot[v]
tot[v]和虚子树大小
s
i
z
[
v
]
siz[v]
siz[v]。子树的大小在
s
p
l
a
y
,
a
c
c
e
s
s
,
l
i
n
k
\mathcal{splay,access,link}
splay,access,link的时候才会改变,在
s
p
l
a
y
splay
splay的时候我们只需要常规
u
p
d
a
t
a
\mathcal{updata}
updata就行了:
t
o
t
[
v
]
=
t
o
t
[
l
s
]
+
t
o
t
[
r
s
]
+
s
i
z
[
v
]
+
1
;
tot[v]=tot[ls]+tot[rs]+siz[v]+1;
tot[v]=tot[ls]+tot[rs]+siz[v]+1;
显然,整个子树的大小是两个儿子整个的大小加上自己的虚树大小。
在
a
c
c
e
s
s
\mathcal{access}
access的时候我们每次都将一条实链变成虚链,将一条虚链变成实链,此时总子树的大小是没变的,改变的是虚子树的大小,我们只需要减掉原来右儿子的大小,加上新右儿子的大小即可:
s
p
l
a
y
(
v
)
,
s
i
z
[
v
]
+
=
t
o
t
[
r
s
]
,
s
i
z
[
v
]
−
=
t
o
t
[
r
s
=
f
]
,
u
p
(
v
)
;
splay(v),siz[v]+=tot[rs],siz[v]-=tot[rs=f],up(v);
splay(v),siz[v]+=tot[rs],siz[v]−=tot[rs=f],up(v);
l i n k \mathcal{link} link的时候就更简单了,直接改自己爸爸的虚子树大小,更新一下就好了。
代码
#include<bits/stdc++.h>
#define ls son[v][0]
#define rs son[v][1]
#define I inline void
#define R register int
using namespace std;
const int M=1e5+5;
int son[M][2],dad[M],siz[M],tot[M],n,q;
bool rev[M];
inline bool notroot(R v){return son[dad[v]][0]==v||son[dad[v]][1]==v;}
I up(R v){tot[v]=tot[ls]+tot[rs]+siz[v]+1;}
I turn(R v){swap(ls,rs);rev[v]^=1;}
I down(R v){if(!rev[v])return;if(ls)turn(ls);if(rs)turn(rs);rev[v]=0;}
I push(R v){if(notroot(v))push(dad[v]);down(v);}
I spin(R v)
{
int f=dad[v],ff=dad[f],k=son[f][1]==v,w=son[v][!k];
if(notroot(f))son[ff][son[ff][1]==f]=v;
son[v][!k]=f;son[f][k]=w;
if(w)dad[w]=f;
dad[f]=v;dad[v]=ff;
up(f);up(v);
}
I splay(R v)
{
push(v);
int f,ff;
while(notroot(v))
{
f=dad[v];ff=dad[f];
if(notroot(f))spin((son[f][0]==v)^(son[ff][0]==f)?v:f);
spin(v);
}
}
I access(R v){for(R f=0;v;v=dad[f=v])splay(v),siz[v]+=tot[rs],siz[v]-=tot[rs=f],up(v);}
I beroot(R v){access(v);splay(v);turn(v);}
I split(R a,R b){beroot(a);access(b);splay(b);}
I link(R x,R y){split(x,y);siz[dad[x]=y]+=tot[x];up(y);}
void in(){scanf("%d%d",&n,&q);}
void ac()
{
char ch[5];
int a,b;
for(R i=1;i<=n;++i)tot[i]=1;
for(R i=1;i<=q;++i)
{
scanf("%s%d%d",ch,&a,&b);
if(ch[0]=='A')link(a,b);
else split(a,b),printf("%lld\n",1ll*(siz[a]+1)*(siz[b]+1));
}
}
int main()
{
in();ac();
return 0;
}