【BZOJ2843】极地旅行社(Link-Cut Tree)

【BZOJ2843】极地旅行社(Link-Cut Tree)

题面

BZOJ

题解

(LCT)模板题呀
没什么好说的了。。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
#define RG register
#define MAX 33333
#define lson (t[x].ch[0])
#define rson (t[x].ch[1])
inline int read()
{
    RG int x=0,t=1;RG char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-')t=-1,ch=getchar();
    while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
    return x*t;
}
struct Node
{
	int ch[2],ff;
	int size,rev,v;
}t[MAX];
int n,m,S[MAX],top;
bool isroot(int x){return t[t[x].ff].ch[0]!=x&&t[t[x].ff].ch[1]!=x;}
void pushup(int x){t[x].size=t[lson].size+t[rson].size+t[x].v;}
void rotate(int x)
{
	int y=t[x].ff,z=t[y].ff;
	int k=t[y].ch[1]==x;
	if(!isroot(y))t[z].ch[t[z].ch[1]==y]=x;t[x].ff=z;
	t[y].ch[k]=t[x].ch[k^1];t[t[x].ch[k^1]].ff=y;
	t[x].ch[k^1]=y;t[y].ff=x;
	pushup(y);pushup(x);
}
void pushdown(int x)
{
	if(!t[x].rev)return;
	swap(lson,rson);
	t[lson].rev^=1;t[rson].rev^=1;
	t[x].rev^=1;
}
void Splay(int x)
{
	S[top=1]=x;
	for(int i=x;!isroot(i);i=t[i].ff)S[++top]=t[i].ff;
	while(top)pushdown(S[top--]);
	while(!isroot(x))
	{
		int y=t[x].ff,z=t[y].ff;
		if(!isroot(y))
			(t[y].ch[1]==x)^(t[z].ch[1]==y)?rotate(x):rotate(y);
		rotate(x);
	}
}
void access(int x){for(int y=0;x;y=x,x=t[x].ff)Splay(x),t[x].ch[1]=y,pushup(x);}
void makeroot(int x){access(x);Splay(x);t[x].rev^=1;}
void split(int x,int y){makeroot(x);access(y);Splay(y);}
void link(int x,int y){makeroot(x);t[x].ff=y;}
void cut(int x,int y){split(x,y);t[y].ch[0]=t[x].ff=0;pushup(y);}
int findroot(int x){access(x);Splay(x);while(lson)x=lson;return x;}
int main()
{
	n=read();
	for(int i=1;i<=n;++i)t[i].v=t[i].size=read();
	char ch[20];int x,y;
	m=read();
	while(m--)
	{
		scanf("%s",ch);		
		x=read(),y=read();
		if(ch[0]=='b')
		{
			if(findroot(x)==findroot(y))puts("no");
			else puts("yes"),link(x,y);
		}
		else if(ch[0]=='p')makeroot(x),t[x].v=y,pushup(x);
		else
		{
			if(findroot(x)!=findroot(y))puts("impossible");
			else
			{
				split(x,y);
				printf("%d
",t[y].size);
			}
		}
	}
	return 0;
}

原文地址:https://www.cnblogs.com/cjyyb/p/8436654.html