并查集 3321是否是一个圈

Your task is so easy. I will give you an undirected graph, and you just need to tell me whether the graph is just a circle. A cycle is three or more nodes V1V2V3, ... Vk, such that there are edges between V1 and V2V2 and V3, ... Vk and V1, with no other extra edges. The graph will not contain self-loop. Furthermore, there is at most one edge between two nodes.

Input

There are multiple cases (no more than 10).

The first line contains two integers n and m, which indicate the number of nodes and the number of edges (1 < n < 10, 1 <= m < 20).

Following are m lines, each contains two integers x and y (1 <= xy <= nx != y), which means there is an edge between node x and node y.

There is a blank line between cases.

Output

If the graph is just a circle, output "YES", otherwise output "NO".

Sample Input

3 3
1 2
2 3
1 3

4 4
1 2
2 3
3 1
1 4

Sample Output

YES
NO

题意:

       给你一个n节点m条边的无向图,问你该图是否正好是一个环(输入不存在自环,没有重复边)?

分析:

       无向图是一个简单环 充要条件是 所以节点的度数==2  且  图连通.

       所以我们只需要记录每个节点的度且用并查集判断最终全图是否只有1个连通分量 即可.
 

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
int father[10000];
int degree[1000];
int m,n;
int findest(int x)
{
    if(father[x]==-1)
    {
        return x;
    }
    else
    {
    father[x]=findest(father[x]);
    }
    return father[x];
}
int bind(int u,int v)
{
    int fu=findest(u);
    int fv=findest(v);
    if(fu!=fv)
    {

        father[fu]=fv;
        return 1;
    }
    return 0;
}
bool ok()
{
    for(int i=1;i<=n;i++)
    {
        if(degree[i]!=2)return false;
    }
    for(int i=2;i<=n;i++)
    {
        if(findest(i)!=findest(1)) return false;
    }
    return true;
}
int main()
{
    int x,y;
    while(cin>>n>>m)
    {
        memset(father,-1,sizeof(father));
        memset(degree,0,sizeof(degree));
        for(int i=1;i<=m;i++)
        {
            cin>>x>>y;
            degree[x]++;
            degree[y]++;
            bind(x,y);
        }
        if(ok())
        {
            cout<<"YES"<<endl;
        }
        else
        {
            cout<<"NO"<<endl;
        }
        for(int i=1;i<=n;i++)
        {
            cout<<father[i]<<" ";
        }
        cout<<endl;
        for(int i=1;i<=n;i++)
        {
            cout<<findest(i)<<" ";
        }
        cout<<endl;
    }
}

可能并查集看起来有点抽象,来画个图:

 https://blog.csdn.net/u013480600/article/details/44131453//这是一位大佬的博客!

猜你喜欢

转载自blog.csdn.net/qq_40859951/article/details/83180933