首页 > 其他 > 详细

【[SDOI2008]洞穴勘测】

时间:2019-02-12 19:08:36      阅读:161      评论:0      收藏:0      [点我收藏+]

题目

由于始终保证连通性于是我们可以用\(LCT\)来维护这个森林

三个操作分别是\(link,cut,findroot\)

代码

#include<iostream>
#include<cstdio>
#define maxn 10005
#define re register
inline int read()
{
    char c=getchar();int x=0;while(c<‘0‘||c>‘9‘) c=getchar();
    while(c>=‘0‘&&c<=‘9‘) x=(x<<3)+(x<<1)+c-48,c=getchar();return x;
}
char opt[15];
int n,m;
int rev[maxn],fa[maxn],ch[maxn][2],st[maxn];
inline int nroot(int x) {return ch[fa[x]][0]==x||ch[fa[x]][1]==x;}
inline void pushdown(int x) {
    if(!rev[x]) return;
    rev[x]=0,rev[ch[x][0]]^=1,rev[ch[x][1]]^=1;
    std::swap(ch[ch[x][0]][0],ch[ch[x][0]][1]);
    std::swap(ch[ch[x][1]][0],ch[ch[x][1]][1]);
}
inline void rotate(int x) {
    int y=fa[x],z=fa[y],k=ch[y][1]==x,w=ch[x][k^1];
    if(nroot(y)) ch[z][ch[z][1]==y]=x;
    ch[x][k^1]=y,ch[y][k]=w;
    fa[w]=y;fa[y]=x,fa[x]=z;
}
inline void splay(int x) {
    int y=x,top=0;
    st[++top]=x;
    while(nroot(y)) st[++top]=fa[y],y=fa[y];
    while(top) pushdown(st[top--]);
    while(nroot(x)) {
        int y=fa[x];
        if(nroot(y)) rotate((ch[fa[y]][1]==y)^(ch[y][1]==x)?x:y);
        rotate(x);
    }
}
inline void access(int x) {
    for(re int y=0;x;y=x,x=fa[x])
        splay(x),ch[x][1]=y;
}
inline void makeroot(int x) {
    access(x);splay(x);rev[x]^=1;std::swap(ch[x][0],ch[x][1]);
}
inline int findroot(int x) {
    access(x),splay(x);
    while(ch[x][0]) pushdown(x),x=ch[x][0];
    return x;
}
inline void link(int x,int y) {
    makeroot(x);
    if(findroot(y)!=x) fa[x]=y;
}
inline void split(int x,int y) {
    makeroot(x);access(y);splay(y);
}
inline void cut(int x,int y) {
    split(x,y);fa[x]=ch[y][0]=0;
}
int main()
{
    n=read(),m=read();
    int x,y;
    while(m--) {
        scanf("%s",opt);x=read(),y=read();
        if(opt[0]==‘D‘) cut(x,y);
        if(opt[0]==‘C‘) link(x,y);
        if(opt[0]==‘Q‘) puts((findroot(x)==findroot(y))?"Yes":"No");
    }
    return 0;
}

【[SDOI2008]洞穴勘测】

原文:https://www.cnblogs.com/asuldb/p/10366722.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!