luogu P4271 [USACO18FEB]New Barns

背景:

h e h e . . . hehe...

题意:

维护一个支持插边的树,同时动态询问输的直径。

思路:

这一种动态的树最好的实现方式自然还是 L C T LCT
我们定义一棵树的直径的所连接的两个点称为端点。
一个性质是若当前连接两棵子树,那么当前输的直径必然来自于这两棵子树的四个端点。
这一道题的特殊性在于只是一个点加入一棵树,那么我们只用维护两次即可(一共就 2 2 个点)。
你还要一个并查集维护祖先,然后将两个端点记录在祖先上。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
	struct node1{int d,fa,size,op,son[2];} tr[300010];
	struct node2{int x,y;} pt[300010];
	int dis[300010],fa[300010];
	int n=0,m;
bool isroot(int x)
{
	return tr[tr[x].fa].son[0]!=x&&tr[tr[x].fa].son[1]!=x;
}
bool isson(int x)
{
	return x==tr[tr[x].fa].son[1];
}
void change(int x)
{
	if(!x)return;
	swap(tr[x].son[0],tr[x].son[1]);
	tr[x].op^=1;
}
void pushup(int x)
{
	int lc=tr[x].son[0],rc=tr[x].son[1];
	tr[x].size=tr[lc].size+tr[rc].size+1;
}
void pushdown(int x)
{
	if(!tr[x].op) return;
	change(tr[x].son[0]),change(tr[x].son[1]);
	tr[x].op=0;
}
void rot(int x)
{
	int w=isson(x),y=tr[x].fa,yy=tr[y].fa;
	tr[y].son[w]=tr[x].son[w^1];
	if(tr[y].son[w]) tr[tr[y].son[w]].fa=y;
	tr[x].fa=yy;
	if(!isroot(y)) tr[yy].son[isson(y)]=x;
	tr[x].son[w^1]=y;tr[y].fa=x;
	pushup(y);
}
int sta[300010];
int top;
void splay(int x)
{
	sta[top=1]=x;
	for(int i=x;!isroot(i);i=tr[i].fa)
		sta[++top]=tr[i].fa;
	while(top) pushdown(sta[top--]);
	for(int y=tr[x].fa;!isroot(x);rot(x),y=tr[x].fa)
		if(!isroot(y)) isson(x)^isson(y)?rot(x):rot(y);
	pushup(x);
}
void access(int x)
{
	for(int y=0;x;y=x,x=tr[x].fa)
		splay(x),tr[x].son[1]=y,pushup(x);
}
void makeroot(int x)
{
	access(x);splay(x);change(x);
}
void link(int x,int y)
{
	makeroot(x);
	tr[x].fa=y;
}
void split(int x,int y)
{
	makeroot(x);access(y);splay(y);
}
int query(int x,int y)
{
	split(x,y);
	return tr[y].size-1;
}
int find(int x)
{
	return x==fa[x]?x:fa[x]=find(fa[x]);
}
int main()
{
	char s[5];
	int x;
	scanf("%d",&m);
	for(int i=1;i<=m;i++)
	{
		tr[i]=(node1){0,0,1,0,0,0};
		pt[i]=(node2){i,i};
		fa[i]=i;
	}
	for(int i=1;i<=m;i++)
	{
		scanf("%s %d",s+1,&x);
		if(s[1]=='B')
		{
			n++;
			if(x==-1) continue;
			int ROOT=find(x);
			link(n,x);
			fa[n]=ROOT;
			int now=query(n,pt[ROOT].x);
			if(now>dis[ROOT]) dis[ROOT]=now,pt[ROOT]=(node2){n,pt[ROOT].x};
			now=query(n,pt[ROOT].y);
			if(now>dis[ROOT]) dis[ROOT]=now,pt[ROOT]=(node2){n,pt[ROOT].y};
		}
		else
		{
			int ROOT=find(x);
			printf("%d\n",max(query(x,pt[ROOT].x),query(x,pt[ROOT].y)));
		}
	}
}

猜你喜欢

转载自blog.csdn.net/zsyz_ZZY/article/details/89488154