洛谷3950 部落冲突(LCT维护连通性)

题目链接

看题目也是个比较裸的题目了
QWQ
不想多说了

开战就是 c u t cut cut,停战就是 l i n k link link

就当记录一个板子了!

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>

using namespace std;

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<<1)+(x<<3)+ch-'0';ch=getchar();}
  return x*f;
}

const int maxn = 6e5+1e2;

int ch[maxn][3];
int fa[maxn],rev[maxn];
int st[maxn],n,m;
int size[maxn];

int son(int x)
{
  if (ch[fa[x]][0]==x) return 0;
  else return 1;
}

bool notroot(int x)
{
	return ch[fa[x]][0]==x || ch[fa[x]][1]==x;
}

void reverse(int x)
{
	swap(ch[x][0],ch[x][1]);
	rev[x]^=1;
}

void pushdown(int x)
{
	if (rev[x])
	{
		if (ch[x][0]) reverse(ch[x][0]);
		if (ch[x][1]) reverse(ch[x][1]);
		rev[x]=0;
	}
}

void rotate(int x)
{
	int y=fa[x],z=fa[y];
	int b=son(x),c=son(y);
	if (notroot(y)) ch[z][c]=x;
	fa[x]=z;
	ch[y][b]=ch[x][!b];
	fa[ch[x][!b]]=y;
	ch[x][!b]=y;
	fa[y]=x;
}

void splay(int x)
{
	int y=x,cnt=0;
	st[++cnt]=y;
	while (notroot(y)) y=fa[y],st[++cnt]=y;
	while (cnt) pushdown(st[cnt--]);
	while (notroot(x))
	{
		int y=fa[x],z=fa[y];
	    int b=son(x),c=son(y);
	    if (notroot(y))
	    {
	    	if (b==c) rotate(y);
	    	else rotate(x);
		}
		rotate(x);
	}
}

void access(int x)
{
	for (int y=0;x;y=x,x=fa[x])
	{
		splay(x);
		ch[x][1]=y;
	}
}

void makeroot(int x)
{
	access(x);
	splay(x);
	reverse(x);
}

int findroot(int x)
{
	access(x);
	splay(x);
	while (ch[x][0])
	{
		pushdown(x);
		x=ch[x][0];
	}
	return x;
}

void split(int x,int y)
{
	makeroot(x);
	access(y);
	splay(y);
}

void link(int x,int y)
{
	makeroot(x);
	if (findroot(y)!=x)
	{
		fa[x]=y;
	}
}

void cut(int x,int y)
{
	split(x,y);
	if (ch[x][1] || ch[x][0] || fa[x]!=y || ch[y][son(x)^1]) return;
	fa[x]=ch[y][0]=0; 
}

int u[maxn],v[maxn];
int tot;

int main()
{
   n=read(),m=read();
   for (int i=1;i<n;i++)
   {
   	  int u=read();
   	  int v=read();
      link(u,v);
   }
   for (int i=1;i<=m;i++)
   {
      char s[10];
      scanf("%s",s+1);
      if (s[1]=='Q')
      {
      	 int x=read(),y=read();
	     if (findroot(x)==findroot(y)) cout<<"Yes"<<"\n";
		 else cout<<"No"<<"\n";
	  }      
	  if (s[1]=='C')
	  {
	  	 int x=read(),y=read();
	  	 u[++tot]=x;
	  	 v[tot]=y;
	  	 cut(x,y);
	  }
	  if (s[1]=='U')
	  {
	  	 int x=read();
	  	 link(u[x],v[x]);
	  }
   }
   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值