码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构与算法问题 欧拉回路

时间:2014-09-13 22:52:26      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   color   io   os   ar   strong   for   数据   art   

题目描述:
    欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
输入:
    测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结束。
输出:
    每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
样例输入:
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0

样例输出:

1

0

#include <iostream>
using namespace std;
const int max = 1001;
int G[max][max];
int du[max];
bool visite[max];
int n, m;
bool judge()
{
	for (int i = 1; i <= n; i++)
	{
		if (du[i] % 2 != 0 || du[i] == 0)
			return false;
	}
	return true;
}

void DFS(int start, int &counts)
{
	for (int i = 1; i <= n; i++)
	{
		if (G[start][i] && !visite[i])
		{
			counts++;
			visite[i] = true;
			DFS(i, counts);
		}
	}
}

int main()
{
	int s, e, counts;
	cin >> n;
	while (n!=0)
	{
		counts = 1;
		for (int i = 0; i <= n;i++)
		for (int j = 0; j <= n; j++)
		{
			G[i][j] = 0;
		}
		for (int i=0;i<=n;i++)
		{
			du[i] = 0;
			visite[i] = false;
		}
		cin >> m;
		for (int i = 0; i <m; i++)
		{
			cin >> s >> e;
			G[s][e] = 1;
			G[e][s] = 1;
			du[s]++;
			du[e]++;
		}
		visite[1] = true;;
		DFS(1, counts);
		if (counts == n&&judge())
			cout << "1" << endl;
		else
			cout << "0" << endl;
		cin >> n;
	}
	return 0;
}


数据结构与算法问题 欧拉回路

标签:style   color   io   os   ar   strong   for   数据   art   

原文地址:http://blog.csdn.net/leviathan_/article/details/39255757

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!