HDU-1878-欧拉回路(并查集)

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

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
#include<iostream>
#include<cstring>
using namespace std;
int n,m;
int pre[1005],cnt,du[1005];
void init()//初始化 
{
	memset(du,0,sizeof(du));
	for(int i = 1; i <= n; i ++)
		pre[i] = i;
}
int root(int x)//查 
{
	if(x!=pre[x])
		pre[x] = root(pre[x]);
	return pre[x];
}
void merge(int x,int y)//并 
{
	int fa = root(x);
	int fb = root(y);
	if(fa!=fb)
	{
		cnt--;
		pre[fa] = fb;
	}
}
int main()
{

	while(~scanf("%d",&n)&&n)
	{
		init();
		cnt = n-1;
		scanf("%d",&m);
		for(int i=0;i<m;++i)
		{
			int x,y;
			scanf("%d %d",&x,&y);
			du[x]++;
			du[y]++;
			merge(x,y);
		}
		if(cnt)//如果边没有都输入过,说明肯定不连通 
		{
			printf("0\n");
			continue;
		}
		int flag = 1;
		for(int i = 0; i < n; i ++)
		{
			if(du[i]%2)//这条边出现了不是偶数次 
			{
				flag = 0;
				break;
			}
		}
		if(flag)
			printf("1\n");
		else
			printf("0\n");
		} 
}

猜你喜欢

转载自blog.csdn.net/qiulianshaonv_wjm/article/details/84582713