Little hope maze - disjoint-set entry

Topic Link

Meaning of the questions:

Given an undirected graph, which determines FIG satisfies: any two points and only one path.

answer:

With disjoint-set and determines whether there is only one root node can be

If you encounter during the first two disjoint-set has been maintained under the same root, then there is only one path to meet, if disjoint-set maintenance is completed, it found that the number of the root node> 1 then is not satisfied

Because the inputs are not directional input, the input tag with the array, for loop determines whether i == f [i]

 

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
int f[maxn],vis[maxn];
int flag=1;
int Find(int x)
{
    return x==f[x]?x:f[x]=Find(f[x]);
}
void join(int x,int y)
{
    int fx=Find(x);
    int fy=Find(y);
    if(fx!=fy)
    {
        f[fx]=fy;
        return ;
    }
    flag=0;
}
int main()
{
    int a,b;
    while(~scanf("%d%d",&a,&b))
    {
        if(a==-1 && b==-1)break;
        if(a==0 && b==0){printf("Yes\n");continue;}
        for(int i=0;i<maxn;i++)f[i]=i,vis[i]=0;
        join(a,b);
        vis[a]=1;
        vis[b]=1;

        while(~scanf("%d%d",&a,&b) && (a || b))
        {
            join(a,b);
            vis[a]=1;
            vis[b]=1;
        }
        if(!flag){printf("No\n");continue;}

        int cnt=0;

        for(int i=0;i<maxn;i++)
        {
            if(vis[i] && f[i]==i)cnt++;
        }

        if(cnt==1)printf("Yes\n");
        else printf("No\n");

    }

    return 0;
}
View Code

 

Guess you like

Origin www.cnblogs.com/j666/p/11609790.html