bzoj2049: [Sdoi2008]Cave 洞穴勘测 LCT

来源:互联网 发布:知秋小说猛兽 编辑:程序博客网 时间:2024/06/10 13:47
由于并查集无法拆边所以考虑用LCT。询问的话首先把x移到LCT的根再把y和根联通。由于无法确定深度,所以两个都要往上遍历。
#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;#define maxn 200010inline int getint(){    int x=0,f=1;char ch=getchar();    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}    return x*f;}int n,m;int next[maxn],tr[maxn][2],fa[maxn],siz[maxn],st[maxn];bool rev[maxn];inline bool isroot(int k){return tr[fa[k]][0]!=k && tr[fa[k]][1]!=k;}void pushdown(int x){    int l=tr[x][0],r=tr[x][1];    if(rev[x])    {        rev[x]=0;rev[l]^=1;rev[r]^=1;        swap(tr[x][0],tr[x][1]);    }}void rotate(int &x){    int l,r,y,z;    y=fa[x];z=fa[y];    if(tr[y][0]==x) l=0;    else l=1; r=l^1;    if(!isroot(y))    {        if(tr[z][0]==y) tr[z][0]=x;        else tr[z][1]=x;    }    fa[x]=z;fa[y]=x;fa[tr[x][r]]=y;    tr[y][l]=tr[x][r];tr[x][r]=y;}void splay(int x){    int top=0;st[++top]=x;    for(int i=x;!isroot(i);i=fa[i])    {        st[++top]=fa[i];    }    for(int i=top;i;i--) pushdown(st[i]);    int y,z;    while(!isroot(x))    {        y=fa[x];z=fa[y];        if(!isroot(y))        {            if((tr[y][0]==x)^(tr[z][0]==y)) rotate(x);            else rotate(y);        }        rotate(x);    }}void access(int x){    int t=0;    while(x)    {        splay(x);        tr[x][1]=t;        t=x;x=fa[x];    }}void makeroot(int x){    access(x);splay(x);rev[x]^=1;}void link(int x,int y){    makeroot(x);fa[x]=y;splay(x);}void cut(int x,int y){    makeroot(x);access(y);splay(y);tr[y][0]=fa[x]=0;}bool query(int x,int y){    access(x);splay(x);    while(y)    {        if(y==x) return true;        else y=fa[y];    }    while(x)    {        if(y==x) return true;        else x=fa[x];    }    return false;}int main(){    n=getint();m=getint();int a,b;char str[10];for(int i=1;i<=m;i++){    scanf("%s",str);    if(str[0]=='Q')        {            a=getint();b=getint();            if(query(a,b)) printf("Yes\n");            else printf("No\n");        }        if(str[0]=='D')        {            a=getint();b=getint();            cut(a,b);        }        if(str[0]=='C')        {            a=getint();b=getint();            link(a,b);        }}    return 0;}

0 0
原创粉丝点击