并查集

好久没有写 并查集的程序了。。  这个 并查集的模板题

#include<iostream>
using namespace std;
    int p[100002],v[100002],u[100002],q[100002];
int f(int n)
{
    return p[n]==n?n:p[n]=f(p[n]);
}

int main()
{
int i,j,n,m;
    while(1)
    {
        
        scanf("%d%d",&u[0],&v[0]);
        if(u[0]==-1&&v[0]==-1)
            break;
        if(u[0]==0&&v[0]==0)
        {
            printf("Yes\n");
            getchar();
            continue;
        }
        i=1;    memset(q,0,sizeof(q)); q[u[0]]=1; q[v[0]]=1;

        while(1)
        {
            scanf("%d%d",&u[i],&v[i]);
            if(u[i]==0&&v[i]==0)
            {
                getchar();
                break;
            }
            q[u[i]]=1; q[v[i]]=1;
            
            i++;
        }
        for(int num=0,j=0;j<100002;j++)
            if(q[j])
                num++;
            if(num!=i+1)
            {
                printf("No\n");
                continue;
            }
        for(j=0;j<100002;j++)
            p[j]=j;
    

        for(j=0;j<i;j++)
        {
            int a=f(u[j]);
            int b=f(v[j]);
            if(a!=b)
                p[b]=a;
            else
            {
                printf("No\n");
                break;
            }
        }
        if(j==i)
         printf("Yes\n");
    }
    return 0;
}
            
        

posted @ 2013-05-26 19:17  galaxy77  阅读(129)  评论(0编辑  收藏  举报