简单的并查集

欧拉回路

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


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

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>

using namespace std;

int pre[1005],book[1005];

void init()
{
	for(int i=0;i<1005;i++)
	{
		pre[i]=i;
	}
}

int find(int x)
{
	return pre[x]==x?x:find(pre[x]);
}

void join(int x,int y)
{
	int xn=find(x);
	int yn=find(y);
	if(xn!=yn)
	{
		pre[y]=x;
	}
	return ;
}

int main()
{
	int n,m;
	while(cin>>n,n)
	{
		cin>>m;
		init();
		fill(book,book+n+1,0);
		for(int i=0;i<m;i++)
		{
			int a,b;
			cin>>a>>b;
			book[a]++;
			book[b]++;
			join(a,b);
		}
		int root=find(1);
		bool flag=1;
		for(int i=1;i<=n;i++)
		{
			if(find(i)!=root||book[i]&1)
				flag=0;
		}
		cout<<flag<<endl;
	}
}

猜你喜欢

转载自blog.csdn.net/guozuofeng/article/details/80642315
今日推荐