BZOJ 4551 HEOI 2016 树 (并查集)

思路:
考虑时光倒流
这不就是并查集裸题了…………….

//By SiriusRen
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 500500
int n,q,xx,yy,v[N],first[N],next[N],tot,fa[N],f[N],ask[N],vis[N],ans[N];char op[N][5];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
void add(int x,int y){v[tot]=y,next[tot]=first[x],first[x]=tot++;}
void dfs(int x){for(int i=first[x];~i;i=next[i])if(v[i]!=fa[x])fa[v[i]]=x,dfs(v[i]);}
int main(){
    freopen("tree.in","r",stdin);
    freopen("tree.out","w",stdout);
    memset(first,-1,sizeof(first));
    scanf("%d%d",&n,&q);
    for(int i=1;i<n;i++)scanf("%d%d",&xx,&yy),add(xx,yy),add(yy,xx);
    dfs(1);
    for(int i=1;i<=q;i++){
        scanf("%s%d",op[i],&ask[i]);
        if(op[i][0]=='C')vis[ask[i]]++;
    }
    f[1]=fa[1]=1;
    for(int i=2;i<=n;i++)if(!vis[i])f[i]=fa[i];else f[i]=i;
    for(int i=q;i;i--){
        if(op[i][0]=='C'&&!--vis[ask[i]])f[ask[i]]=fa[ask[i]];
        else ans[i]=find(ask[i]);
    }
    for(int i=1;i<=q;i++)
        if(op[i][0]=='Q')printf("%d\n",ans[i]);
}

这里写图片描述

posted @ 2017-01-02 14:56  SiriusRen  阅读(78)  评论(0编辑  收藏  举报