【动态树】[BZOJ2049] Cave 洞穴勘测

就是个动态树的模版,判断两个是否有路就是先
access(第一个节点) 然后 Splay(第一个节点)
然后最左边的节点就是根
然后同理第二个 判断两个的根是否相同就行了

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10000;
int ch[MAXN+10][2], Fa[MAXN+10];
int que[MAXN+10];
bool rev[MAXN+10];
bool isroot(int u){return ch[Fa[u]][0] != u && ch[Fa[u]][1] != u;}
void Rotate(int u){
    int x = Fa[u], y = Fa[x];
    bool md = ch[x][1] == u;
    Fa[u] = y;
    if(!isroot(x)) ch[y][ch[y][1] == x] = u;
    ch[x][md] = ch[u][!md]; Fa[ch[u][!md]] = x;
    ch[u][!md] = x; Fa[x] = u;
}
void push_down(int u){
    if(rev[u]){
        rev[u] ^= 1; rev[ch[u][0]] ^= 1; rev[ch[u][1]] ^= 1;
        swap(ch[u][0], ch[u][1]);
    }
}
void Splay(int u){
    int now = u;
    que[0] = 1; que[1] = now;
    while(!isroot(now)){
        que[++que[0]] = Fa[now];
        now = Fa[now];
    }
    for(;que[0];que[0]--) push_down(que[que[0]]);
    while(!isroot(u)){
        int x = Fa[u], y = Fa[x];
        if(!isroot(x)){
            if((ch[x][0] == u) ^ (ch[y][0] == x)) Rotate(u);
            else Rotate(x);
        }
        Rotate(u);
    }
}
void access(int u){
    int up = 0;
    while(u != 0){
        Splay(u);
        ch[u][1] = up;
        up = u; u = Fa[u];
    }
}
void root(int u){
    access(u);
    Splay(u);
    rev[u] ^= 1;
}
void Link(int x, int y){
    root(x);
    Fa[x] = y;
    Splay(x);
}
void Cut(int x, int y){
    root(x);
    access(y);
    Splay(y);
    ch[y][0] = Fa[x] = 0;
}
bool Query(int x, int y){
    access(x); Splay(x);
    int u = x;
    while(ch[u][0]) u = ch[u][0];

    access(y); Splay(y);
    int u1 = y;
    while(ch[u1][0]) u1 = ch[u1][0];

    return u == u1;
}
int main(){
    int n, m, a, b;
    scanf("%d %d", &n, &m);
    char ord[20];
    for(int i=0;i<m;i++){
        scanf("%s", ord);
        scanf("%d %d", &a, &b);
        if(ord[0] == 'C') Link(a,b);
        else if(ord[0] == 'D') Cut(a,b);
        else printf("%s", Query(a,b) ? "Yes\n\0":"No\n\0");
    }

    return 0;
}

posted on 2015-04-11 11:24  JeremyGuo  阅读(...)  评论(... 编辑 收藏

导航

统计