[USACO18FEB]New Barns P

题目的意思是让我们动态维护直径。

很容易得到以下两个定理:
1.两棵树合并以后的直径端点是原来两棵树的四个直径端点中的两个;
2.距离一个点最远的点一定是一个直径的端点。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
template<typename T>inline void qr(T &x){
	x=0;int f=0;char s=getchar();
	while(s<'0'||'9'<s)f|=s=='-',s=getchar();
	while('0'<=s&&s<='9')x=x*10+s-48,s=getchar();
	x=f?-x:x;
}
const int mxn=1e5+10;
int n,q,sta[mxn];bool rv[mxn];
int fa[mxn],ch[mxn][2],c[mxn],dx[mxn],dy[mxn];
#define lc ch[x][0]
#define rc ch[x][1]
#define ls(x) ch[x][0]
#define rs(x) ch[x][1]
bool nrt(int x){return ls(fa[x])==x||rs(fa[x])==x;}
void crv(int x){
	if(!x)return;
	swap(lc,rc);rv[x]^=1;
}
void pushdown(int x){
	if(rv[x])
		crv(lc),crv(rc),rv[x]=0;
	dx[lc]=dx[rc]=dx[x];
	dy[lc]=dy[rc]=dy[x];
}
void update(int x){
	c[x]=c[lc]+c[rc]+1;
}
void rotate(int x){
	int y=fa[x],z=fa[y],w=rs(y)==x;
	if(nrt(y))ch[z][rs(z)==y]=x;fa[x]=z;
	fa[ch[y][w]=ch[x][1-w]]=y;
	ch[x][1-w]=y;fa[y]=x;
	update(y);
}
void splay(int p){
	int x=p,tp=0;
	sta[++tp]=x;
	while(nrt(x))sta[++tp]=x=fa[x];
	while(tp)pushdown(sta[tp--]);x=p;
	while(nrt(x)){
		int y=fa[x],z=fa[y];
		if(nrt(y))
			(rs(z)==y)^(rs(y)==x)?rotate(x):rotate(y);
		rotate(x);
	}
	update(x);
}
void access(int x){
	for(int y=0;x;x=fa[y=x])
		splay(x),rc=y,update(x);
}
void makeroot(int x){
	access(x);splay(x);crv(x);
}
int calc(int x,int y){
	makeroot(x);
	access(y);
	splay(y);
	return c[y];
}
int main(){
	int q;qr(q);
	while(q--){
		char s[2];scanf("%s",s);
		if(s[0]=='B'){
			n++;
			int x;qr(x);
			dx[n]=dy[n]=n;
			c[n]=1;
			if(x!=-1){
				makeroot(x);
				fa[n]=x;
				int pre=calc(dx[x],dy[x]),t;
				int hx=dx[x],hy=dy[x];
				if((t=calc(dx[x],n))>pre){
					pre=t;
					hx=dx[x],hy=n;
				}
				if((t=calc(dy[x],n))>pre){
					pre=t;
					hx=n,hy=dy[x];
				}
				makeroot(x);
				dx[x]=hx,dy[x]=hy;
			}
		}
		else{
			int x;qr(x);makeroot(x);
			printf("%d\n",max(calc(x,dx[x]),calc(x,dy[x]))-1);
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值