HDU

欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?

Input

测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结 
束。

Output

每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。 

Sample Input

3 3
1 2
1 3
2 3
3 2
1 2
2 3
0

Sample Output

1
0

题解:我们知道欧拉回路主要是有两个条件:1.连通图 。2.所有点的度都为偶数。然后此题就可解了

代码如下:

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

using namespace std;
int pre[10005];
int find (int x)
{
	if(x==pre[x])
	return x;
	else
	{
		return pre[x]=find(pre[x]);
	}
}
void merge(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy)
	{
		pre[fx]=fy;
	}
}
bool connect(int n)
{
	int cnt=0;
	for(int t=1;t<=n;t++)
	{
		if(pre[t]==t)
		cnt++;
	
	}
	
	
	if(cnt==1)
	{
		return true;
	}
	else
	{
		return false;
	}
	
}
int main()
{
	int n,m;
	int deg[100005];
	while(scanf("%d",&n))
	{
		
		if(n==0)
		{
			break;
		}
		scanf("%d",&m);
		for(int t=1;t<=n;t++)
		{
			pre[t]=t;
		}
		for(int t=1;t<=n;t++)
		{
			deg[t]=0;
		}
		int a,b;
		for(int t=0;t<m;t++)
		{
			scanf("%d%d",&a,&b);
			deg[a]++;
			deg[b]++;
			merge(a,b);
		}
		int flag=0;
		for(int t=1;t<=n;t++)
		{
			if(deg[t]%2!=0)
			{
				flag=1;
			}
		}
	     if(!flag&&connect(n))
	     {
	     	printf("1
");
		 }
		 else
		 {
		 	printf("0
");
		 }
		
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Staceyacm/p/10782076.html