1. 程式人生 > >1272(並查集判斷是否成環)

1272(並查集判斷是否成環)

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int fa[100005],vis[100005],flag;//flag判斷是否成環
int n , m;
int findroot(int x)
{
    if(fa[x] == x)
        return x;
    else
        return fa[x] = findroot(fa[x]);
}
void merge(int x ,int y)
{
    int fax = findroot(x);
    int fay = findroot(y);
    if(fax == fay)
        flag = 1;
    fa[fay] = fax;
}
int main(void)
{
    while(scanf("%d %d",&n,&m) != EOF)
    {
        for(int i = 1 ;  i <= 100005 ; i ++)
        {
            fa[i] = i;
            vis[i] = 0;
        }
        if(n == -1 && m == -1)
            return 0;
        merge(n,m);
        vis[n] = 1;
        vis[m] = 1;
        if(n == 0 && m == 0)
        {
            cout<<"Yes"<<endl;
            continue;
        }
        else
        {
            while(scanf("%d %d",&n , &m) != EOF)
            {
                if(n != 0 && m != 0)
                {
                    merge(n , m);
                    vis[n] = 1 ;
                    vis[m] = 1;
                }
                if(n == 0 && m == 0)
                {
                    int sum = 0;
                    for(int i = 1 ; i <= 100005 ; i ++)
                        findroot(i);
                    for(int i = 1 ; i <= 100005 ; i ++)
                    {
                        if(vis[i] && fa[i] == i)
                            sum ++;
                    }
                    if(sum > 1 || flag)//看所有房間是否在同一個集合,並判斷此集合是否成環
                    {
                        cout<<"No"<<endl;
                        flag = 0;
                        break;
                    }
                    else
                    {
                        cout<<"Yes"<<endl;
                        flag = 0;
                        break;
                    }
                }
            }
        }
    }
    return 0;
}