ZOJ 3321 Circle【并查集】

解题思路:给定n个点,m条边,判断是否构成一个环

注意到构成一个环,所有点的度数为2,即一个点只有两条边与之相连,再有就是判断合并之后这n个点是否在同一个连通块

Circle

Time Limit: 1 Second      Memory Limit: 32768 KB

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 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 <= 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
#include<iostream>  
#include<cstdio>  
#include<cstring>  
#include<algorithm>  
using namespace std;
int degree[10010],pre[10010];

int find(int root){ return root == pre[root] ? root : pre[root] = find(pre[root]); }
void unionroot(int x,int y)
{
	int root1=find(x);
	int root2=find(y);
	if(root1!=root2)
	pre[root1]=root2;
}

int main()
{
	int m,n,u,v,i,j;
	while(scanf("%d %d",&n,&m)!=EOF)
	{
		int flag=1;
		memset(degree,0,sizeof(degree));
		for(i=1;i<=10010;i++)
		pre[i]=i;
		for(i=1;i<=m;i++)
		{
			scanf("%d %d",&u,&v);
			degree[u]++;
			degree[v]++;
			unionroot(u,v);	
		}
		
		for(i=1;i<=n;i++)
		{
			if(degree[i]!=2)
			{
				flag=0;
				break;
			}
			if(find(i)!=find(n))
			{
				flag=0;
				break;
			}
		}
		if(flag)
		printf("YES\n");
		else
		printf("NO\n");		
	}
}

  

 

转载于:https://www.cnblogs.com/wuyuewoniu/p/4254667.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。 经导师精心指导并认可、获 98 分的毕业设计项目!【项目资源】:微信小程序。【项目说明】:聚焦计算机相关专业毕设及实战操练,可作课程设计与期末大作业,含全部源码,能直用于毕设,经严格调试,运行有保障!【项目服务】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值