有了LCT这不就是思博题了吗
#include <bits/stdc++.h>
using namespace std;
const int N = 1000000;
int n,m,t1,t2,t3;
char op[5];
struct LinkCutTree {
int top, q[N], ch[N][2], fa[N], rev[N];
inline void pushup(int x) {
}
inline void pushdown(int x) {
if(!rev[x])
return;
rev[ch[x][0]]^=1;
rev[ch[x][1]]^=1;
rev[x]^=1;
swap(ch[x][0],ch[x][1]);
}
inline bool isroot(int x) {
return ch[fa[x]][0]!=x && ch[fa[x]][1]!=x;
}
inline void rotate(int p) {
int q=fa[p], y=fa[q], x=ch[fa[p]][1]==p;
ch[q][x]=ch[p][x^1];
fa[ch[q][x]]=q;
ch[p][x^1]=q;
fa[q]=p;
fa[p]=y;
if(y)
if(ch[y][0]==q)
ch[y][0]=p;
else if(ch[y][1]==q)
ch[y][1]=p;
pushup(q);
pushup(p);
}
inline void splay(int x) {
q[top=1]=x;
for(int i=x; !isroot(i); i=fa[i])
q[++top]=fa[i];
for(int i=top; i; i--)
pushdown(q[i]);
for(; !isroot(x); rotate(x))
if(!isroot(fa[x]))
rotate((ch[fa[x]][0]==x)==(ch[fa[fa[x]]][0]==fa[x])?fa[x]:x);
}
void access(int x) {
for(int t=0; x; t=x,x=fa[x])
splay(x),ch[x][1]=t,pushup(x);
}
void makeroot(int x) {
access(x);
splay(x);
rev[x]^=1;
}
int find(int x) {
access(x);
splay(x);
while(ch[x][0])
x=ch[x][0];
return x;
}
void split(int x,int y) {
makeroot(x);
access(y);
splay(y);
}
void cut(int x,int y) {
split(x,y);
if(ch[y][0]==x)
ch[y][0]=0, fa[x]=0;
}
void link(int x,int y) {
makeroot(x);
fa[x]=y;
}
} tree;
vector <pair<int,int> > vc;
int main() {
scanf("%d%d",&n,&m);
for(int i=1; i<n; i++) {
scanf("%d%d",&t1,&t2);
tree.link(t1,t2);
}
for(int i=1; i<=m; i++) {
scanf("%s",op);
if(op[0]=='Q') {
scanf("%d%d",&t1,&t2);
if(tree.find(t1) == tree.find(t2))
printf("Yes\n");
else
printf("No\n");
}
if(op[0]=='C') {
scanf("%d%d",&t1,&t2);
tree.cut(t1,t2);
vc.push_back(make_pair(t1,t2));
}
if(op[0]=='U') {
scanf("%d",&t1);
t2=vc[t1-1].first, t3=vc[t1-1].second;
tree.link(t2,t3);
}
}
}
原文地址:https://www.cnblogs.com/mollnn/p/11704797.html
时间: 2024-11-03 14:03:38