Graph Theory NO.2 HDU_1272_小希的迷宫_并查集

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int father[100009];
int mark[100009];
int Init()
{
    for(int i=1;i<100009;i++)
    {
        father[i]=i;
    }
    return 0;
}
int Find(int n)
{
    if(father[n]!=n)
    {
        father[n]= Find(father[n]);
    }
    return father[n];
}
int Union(int a,int b)
{
    if(a!=b)
    {
        father[a]=b;
    }
    return 0;
}
int main()
{
    int i=0;
    int flag=0;
    int count=0;
    int a,b;
    Init();
    while(1)
    {
        scanf("%d%d",&a,&b);
        if(a==-1&&b==-1)
        {
            break;
        }
        if(a&&b)
        {
            mark[i++]=a;
            mark[i++]=b;
            if(Find(a)==Find(b))
            {
                flag=1;
            }
            Union(Find(a),Find(b));
            //printf("%d %d\n",father[a],father[b]);
        }
        if(a==0&&b==0)
        {
            if(i==0)
            {
                printf("Yes\n");
                continue;
            }
            for(int j=0;j<i;j++)
            {
                if(father[mark[j]]==mark[j])
                count++;
               // printf("=%d %d\n",mark[j],father[mark[j]]);

            }
            if(flag==0&&count==1)
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
            i=0;count=0;flag=0;Init();
        }

    }
    return 0;
}
/*
1 4 1 2 2 12 12 13 12 15 15 11 11 3 3 2 4 5 5 9 5 6 6 7 6 8 9 10 0 0
1 2 1 3 1 4 2 8 8 9 3 5 5 10 10 12 4 6 6 11 4 7
0 0
1 2 3 1 4 1 8 2 8 9 5 3 5 10 10 12 6 4 6 11 4 7
0 0
1 4 2 1 2 12 12 13 15 12 15 11 11 3 2 3 4 5 5 9 5 6 6 7 6 8 9 10
0 0
6 8  5 3  5 2  6 4
5 6  0 0
8 1  7 3  6 2  8 9  7 5
7 4  7 8  7 6  0 0
3 8  6 8  6 4
5 3  5 6  5 2  0 0
1 2 3 4 0 0
1 2 0 0
nyynyynny
*/

猜你喜欢

转载自blog.csdn.net/m0_37862025/article/details/78187028