hdu1272 并查集

今天水题作了一大推。。

本题有个坑一直没发现。。上代码啦

#include<iostream>
#include<cstring>
using namespace std;
#define MAXN 100005
int a,b;
int F[MAXN];
bool circle;
bool vis[MAXN];
int edge,v;

int find(int x){
    if(F[x]==0) return x;
    return F[x]=find(F[x]);
}
void merge(int a,int b){
    int t1=find(a);
    int t2=find(b);
    if(t1!=t2) F[t1]=t2,edge++;
    else circle=1;    
}

void init(){
    memset(F,0,sizeof F);
    memset(vis,0,sizeof vis);
    circle=edge=v=0;    
}
int main(){
    int a,b;
    while(1){
        init();
        scanf("%d%d",&a,&b);
        if(a==0||b==0){
            puts("Yes");
            continue;
        }
        if(a==-1&&b==-1) break;
        vis[a]=vis[b]=1;
        merge(a,b);
        while(1){
            scanf("%d%d",&a,&b);
            if(a==0&&b==0) break;
            vis[a]=vis[b]=1;
            merge(a,b);
        }
        for(int i=0;i<MAXN;i++)
            if(vis[i]) v++;
        if(!circle && edge+1==v)
            puts("Yes");
        else 
            puts("No");
    }
    return 0;
}

 

posted on 2018-10-19 16:35  zsben  阅读(147)  评论(0编辑  收藏  举报

导航