hdu 1878 欧拉回路 【并查集+欧拉】

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1878

                                                                                          欧拉回路

                            Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
                                                   Total Submission(s): 18533    Accepted Submission(s): 7199

 

Problem Description

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

 

Input

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

 

Output

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

扫描二维码关注公众号,回复: 2781482 查看本文章
 

Sample Input

 

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

 

Sample Output

 

1 0

思路:本来想dfs跑一遍的,可惜自己太渣,挖了好几发,先给个并查集的,dfs以后补上。我真是渣,唉,dfs

//如果一个图是欧拉图的话,无奇度顶点为欧拉回路,有两个
//奇度顶点的话为欧拉通路,这很重要。 
#include<bits/stdc++.h>
#include<string.h>
#include<stdio.h>
using namespace std;
const int maxn = 1e3+5;
int bin[maxn],a[maxn];
int ans1,ans2,n,m,x,y;
int find(int x)
{
	return bin[x]==x?x:find(bin[x]);  //递归找老大 
 } 
void merge(int x,int y)
{
	int fx=find(x);
	int fy=find(y);
	if(fx!=fy)
	  bin[fx]=fy; //左右合并都可以 
}
void init(int n)
{
	for(int i=1;i<=n;i++)
	{
		if(bin[i]==i)
		  ans1++;  //统计根节点的集合
		if(a[i]%2==1)
		  ans2++;  //由欧拉定理统计奇度顶点个数 
	}
}
int main()
{        
    while(scanf("%d %d",&n,&m)!=EOF)
	{  
	    if(n==0)  break;
	    ans1=0,ans2=0;
		memset(a,0,sizeof(a));
		for(int i=1;i<=n;i++)
		  bin[i]=i;  //每个集合的老大都假设为自己
		for(int i=0;i<m;i++) 
		{
			scanf("%d %d",&x,&y);
			merge(x,y);
			a[x]++;
			a[y]++;
		}
		init(n);
		if(ans1==1&&ans2==0)
		  printf("1\n");
		else
		  printf("0\n"); 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LOOKQAQ/article/details/81706362