题目42 一笔画问题(NYOJ)

一笔画问题

时间限制:3000 ms  |  内存限制:65535 KB

难度:4

描述

zyc从小就比较喜欢玩一些小游戏,其中就包括画一笔画,他想请你帮他写一个程序,判断一个图是否能够用一笔画下来。

规定,所有的边都只能画一次,不能重复画。

输入

第一行只有一个正整数N(N<=10)表示测试数据的组数。
每组测试数据的第一行有两个正整数P,Q(P<=1000,Q<=2000),分别表示这个画中有多少个顶点和多少条连线。(点的编号从1到P)
随后的Q行,每行有两个正整数A,B(0<A,B<P),表示编号为A和B的两点之间有连线。

输出

如果存在符合条件的连线,则输出"Yes",
如果不存在符合条件的连线,输出"No"。

样例输入

2
4 3
1 2
1 3
1 4
4 5
1 2
2 3
1 3
1 4
3 4

样例输出

No
Yes

来源

[张云聪]原创

上传者

张云聪

问题链接:题目42 一笔画问题(NYOJ)

问题分析:欧拉定理:如果一个网络是连通的并且奇顶点的个数等于0或2,那么它可以一笔画出;否则它不可以一笔画出

程序说明:程序使用并查集判断图是否连通

AC的C++程序:

#include<iostream>
#include<cstring>
#include<cstdio>

using namespace std;
int pre[1003];
void init(int n)
{
	for(int i=0;i<=n;i++)
	  pre[i]=i;
}

int find(int x)
{
	int r=x;
	while(r!=pre[r])
	  r=pre[r];
	//路径压缩 
	while(x!=pre[x]){
		int i=pre[x];
		pre[x]=r;
		x=i;
	}
	return r;
} 
 
bool join(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy){//采用值大为祖先 
		if(fx>fy){
			int temp=fx;
			fx=fy;
			fy=temp;
		}
		pre[fx]=fy;
		return true;
	}
	return false;
}

int main()
{
	int n,p,q,a,b;
	int degree[1003];
	scanf("%d",&n);
	while(n--){
		scanf("%d%d",&p,&q);
		init(p);
		memset(degree,0,sizeof(degree));
		int count=0;
		while(q--){
			scanf("%d%d",&a,&b);
			degree[a]++;
			degree[b]++;
			if(join(a,b))
			  count++;
		}
		int cnt=0;
		for(int i=1;i<=p;i++)
		  if(degree[i]%2)//度数是奇数的点 
		    cnt++;
		if(count==p-1&&(cnt==0||cnt==2))//连通且有0个或者两个度数为奇数的点
		  printf("Yes\n");
		else
		  printf("No\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SongBai1997/article/details/81384947