P4299 首都 题解
本题要支持连边的情况下动态维护重心。
首先注意到重心的性质:
- 两棵树用一条边连通, 则新重心在原重心之间的路径上。
- 重心最大子树的大小
\leq 总大小一半。
说一下性质 1:树连接一个点后,重心要偏移也是往那个连接的点偏移。连接树同理,改为一个一个加点即可。
于是我们很容易想到将这条链 split 出来,二分找到重心。
具体的,维护每个结点的子树大小(含虚子树)。我们先找到 splay 的根,如果不是重心,就跳到大小更大的实儿子去找。
不必考虑虚子树,因为虚子树不可能是最大子树。因为如果是,就得往那个子树跳了,不就跳出这条链了?
所以具体的,在 splay 中,用
#include<cstdio>
#include<algorithm>
using namespace std;
#define N 100005
namespace lct
{
struct node
{
int size,more;
int fa,son[2];
int tag;
} tr[N];
int idx;
int bcj[N],zx[N];
int find(int x){return bcj[x]==x?x:bcj[x]=find(bcj[x]);}
bool ckrt(int x){return !tr[x].fa||tr[tr[x].fa].son[tr[tr[x].fa].son[1]==x]!=x;}
void pushup(int x)
{
tr[x].size=tr[tr[x].son[0]].size+1+tr[tr[x].son[1]].size+tr[x].more;
}
void swp(int x)
{
swap(tr[x].son[0],tr[x].son[1]);
tr[x].tag^=1;
}
void pushdown(int x)
{
if(tr[x].tag)
swp(tr[x].son[0]),
swp(tr[x].son[1]),
tr[x].tag=0;
}
void pushall(int x)
{
if(!ckrt(x)) pushall(tr[x].fa);
pushdown(x);
}
void rotate(int x)
{
int y=tr[x].fa,z=tr[y].fa,t=tr[y].son[1]==x,t2=ckrt(y);
int a=tr[x].son[t^1];
tr[x].son[t^1]=y,tr[y].fa=x;
tr[y].son[t]=a,tr[a].fa=y;
if(!t2) tr[z].son[tr[z].son[1]==y]=x;
tr[x].fa=z;
pushup(y),pushup(x);
}
void splay(int x)
{
pushall(x);
while(!ckrt(x))
{
int y=tr[x].fa,z=tr[y].fa;
if(!ckrt(y)) rotate(tr[y].son[1]==x^tr[z].son[1]==y?x:y);
rotate(x);
}
}
void access(int x)
{
for(int y=0;x;y=x,x=tr[x].fa)
splay(x),
tr[x].more+=tr[tr[x].son[1]].size-tr[y].size,
tr[x].son[1]=y;
}
void mkrt(int x)
{
access(x),splay(x),swp(x);
}
void split(int x,int y)
{
mkrt(x),access(y),splay(y);
}
void link(int x,int y)
{
mkrt(x),mkrt(y);
tr[y].fa=x;
tr[x].more+=tr[y].size;
pushup(x);
int a=zx[find(x)],b=zx[find(y)];
split(a,b);
int t=b;
int lsum=0,rsum=0,sum=tr[b].size,ans=2e9;
while(t)
{
pushdown(t);
int fl=lsum+tr[tr[t].son[0]].size,fr=rsum+tr[tr[t].son[1]].size;
if(fl<=sum>>1&&fr<=sum>>1)
ans=min(ans,t);
// else if(ans!=2e9) break;
if(fl>=fr)
rsum+=tr[tr[t].son[1]].size+tr[t].more+1,
t=tr[t].son[0];
else
lsum+=tr[tr[t].son[0]].size+tr[t].more+1,
t=tr[t].son[1];
}
zx[bcj[find(x)]=find(y)]=ans;
splay(ans);
}
};
namespace code
{
int *bcj=lct::bcj,*zx=lct::zx;
lct::node *tr=lct::tr;
using lct::find;
using lct::link;
int n,q,xors;
signed main()
{
scanf("%d%d",&n,&q);
for(int i=1;i<=n;++i)
xors^=i,
tr[i].size=1,
bcj[i]=i,
zx[i]=i;
while(q--)
{
char c=getchar();
if(c=='A')
{
int x,y;
scanf("%d%d",&x,&y);
xors^=zx[find(x)]^zx[find(y)];
link(x,y);
xors^=zx[find(x)];
}
else if(c=='Q')
{
int x;
scanf("%d",&x);
printf("%d\n",zx[find(x)]);
}
else if(c=='X')
printf("%d\n",xors);
else ++q;
}
return 0;
}
}
signed main()
{
code::main();
return 0;
}/*
10 10 Xor Q 1 A 10 1 A 1 4 Q 4 Q 10 A 7 6 Xor Q 7 Xor
11
1
1
1
2
6
2
3 3 A 1 3 A 2 3 Q 2
3
3 3 A 3 2 A 1 3 Xor
3
5 7 Q 4 Q 5 Q 3 Xor A 5 4 A 1 4 Xor
4
5
3
1
5
5 3 A 5 4 A 1 4 Xor
5
5 4 A 3 5 A 4 5 A 1 3 Xor
1
*/