zoj 3321 Circle【并查集】



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 nodesV1, V2,V3, ... Vk, such that there are edges betweenV1 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 nodex 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条边组成无向图,求该无向图是不是一个环,是输出“YES”, 否输出“NO”;

分析:记录每个节点的度【如果能是环,则每个节点的度均为2】,然后在判断是否左右结点都在这个图中;

可以在输入边时记录该边连接的两个结点的度,判断所有点是否在一个图中,可以用并查集~~~

已Accept代码【c++】

#include <cstdio>
#include <cstring>
using namespace std;

int n, m;
int pre[11], map[11];

int Find(int x) {
	int r = x;
	while(r != pre[r])
		r = pre[r];
	int i = x, j;
	while(i != r) {
		j = pre[i];
		pre[i] = r;
		i = j;
	}
	return r;
}

void Join(int x, int y) {
	int fx = Find(x);
	int fy = Find(y);
	if(fx != fy)
		pre[fx] = fy;
}

bool Ok() {
	for(int i = 1; i <= n; i++)
		if(map[i] != 2)
			return false;
	int ok = Find(1);
	for(int i = 2; i <= n; i++)
		if(ok != Find(i))
			return false;
	return true;
}

int main() {
	int a, b;
	while(scanf("%d%d", &n, &m) != EOF) {
		for(int i = 1; i <= n; i++) {
			pre[i] = i;
			map[i] = 0;
		}
		for(int i = 0; i < m; i++) {
			scanf("%d %d", &a, &b);
			Join(a, b);
			map[a]++;
			map[b]++;
		}
		printf("%s\n", Ok() ? "YES" : "NO");
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值