【bzoj1180】OTOCI LCT

AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=1180

【吐槽】

馬上就要回宿舍了,於是蒟蒻在此水一道模板題。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<algorithm>
using namespace std;
#define FILE "read"
#define MAXN 30010
#define up(i,j,n) for(int i=j;i<=n;++i)
#define dn(i,j,n) for(int i=j;i>=n;--i)
namespace INIT{
	char buf[1<<15],*fs,*ft;
	inline char getc(){return (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<15,stdin),fs==ft))?0:*fs++;}
	inline int read(){
		int x=0,f=1;  char ch=getchar();
		while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
		while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
		return x*f;
	}
}using namespace INIT;
int n,m,a[MAXN],f[MAXN],vis[MAXN],sum[MAXN],stack[MAXN],son[MAXN][2];
namespace Link_Cut_Tree{
	bool get(int x){return son[f[x]][1]==x;}
	bool isroot(int x){return son[f[x]][0]!=x&&son[f[x]][1]!=x;}
	void updata(int x){sum[x]=sum[son[x][0]]+sum[son[x][1]]+a[x];}
	void pushdown(int x){
		if(vis[x]){
			swap(son[x][0],son[x][1]);
			vis[son[x][0]]^=1; vis[son[x][1]]^=1;
			vis[x]=0;
		}
	}
	void rotate(int x){
		int y=f[x],z=f[y],which=get(x);
		if(!isroot(y))  son[z][son[z][1]==y]=x;
		son[y][which]=son[x][which^1];  f[son[y][which]]=y;
		son[x][which^1]=y;  f[y]=x;  f[x]=z;
		updata(y);  updata(x);
	}
	void splay(int x){
		int top(0); stack[++top]=x;
		for(int i=x;!isroot(i);i=f[i])  stack[++top]=f[i];
		dn(i,top,1)  pushdown(stack[i]);
		for(int y=f[x];!isroot(x);rotate(x),y=f[x])
			if(!isroot(y))  rotate(get(x)==get(y)?y:x);
	}
	void access(int x){for(int temp(0);x;temp=x,x=f[x])splay(x),son[x][1]=temp,updata(x);}
	void reverse(int x){access(x);splay(x);vis[x]^=1;}
	void linkk(int x,int y){reverse(x);f[x]=y;}
	void split(int x,int y){reverse(x);access(y);splay(y);}
	int find(int x){access(x);splay(x);while(son[x][0])x=son[x][0];return x;}
}
int main(){
	freopen(FILE".in","r",stdin);
	freopen(FILE".out","w",stdout);
	using namespace Link_Cut_Tree;
	n=read(); up(i,1,n)  a[i]=sum[i]=read();
	m=read();
	up(i,1,m){
		char ch[15];  scanf("%s",ch); int x=read(),y=read();
		if(ch[0]=='b'){if(find(x)==find(y))puts("no");else puts("yes"),linkk(x,y);}
		else if(ch[0]=='p'){reverse(x);  a[x]=y;  updata(x);}
		else{
			if(find(x)!=find(y))puts("impossible");
			else split(x,y),printf("%d\n",sum[y]);
		}
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章