zoj 3321並查集判環
阿新 • • 發佈:2018-11-08
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 V1, V2, V3, ... Vk, such that there are edges between V1 and V2, V2 and V3, ... Vk
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
Following are m lines, each contains two integers x and y (1 <= x, y <= n, x != 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
判斷是否為環,入度為2,並且只有一個聯通分量
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int father[105];
int du[105];
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
void unionn(int x,int y)
{
int fa=find(x);
int fb=find(y);
if(fa!=fb)
father[fb]=fa;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{int flag=0;
memset(du,0,sizeof(du));
memset(father,0,sizeof(father));
for(int i=1;i<=n;i++)
father[i]=i;
int a,b;
for(int i=1;i<=m;i++)
{
scanf("%d%d",&a,&b);
unionn(a,b);
du[a]++;
du[b]++;
}
for(int i=1;i<=n;i++)
{
if(du[i]!=2)
{flag=1;
break;
}
if(find(i)!=find(n))
{
flag=1;
break;
}
}
if(flag)
printf("NO\n");
else
printf("YES\n");
}
return 0;
}