poj 1041 John's trip(欧拉回路入门题)

 

经典的欧拉回路题

http://poj.org/problem?id=1041

 

欧拉回路:每条边经过一次且仅一次的称为欧拉回路(euler cycle, euler circuit)。

存在欧拉回路的充要条件:每个点的度数都是偶数, 且图连通。

#include "iostream"
#include "stdio.h"
#include "string.h"
#include "algorithm"
using namespace std;

int G[50][2000];  //G[点][边] = 点,这样是为了能方便让边lexicographically输出
bool vis[2000];   //记录访问边的情况
int degree[50];
int stack[2000], top;

int max(int a, int b)
{
	return a > b ? a : b;
}

void euler(int cur, int nRoads)  //cur当前访问的点
{
	for(int i = 1; i <= nRoads; i++)
	{
		if(!vis[i] && G[cur][i])  //若相邻边未访问过
		{
			vis[i] = true;
			euler(G[cur][i], nRoads);
			stack[++top] = i;
		}
	}
}

int main()
{
	int x, y, z, nRoads, nPoints, start;
	while(scanf("%d%d", &x, &y) && x && y)
	{
		nRoads = nPoints = top = 0;
		memset(vis, false, sizeof(vis));
		memset(degree, 0, sizeof(degree));
		memset(G, 0, sizeof(G));

		start = x < y ? x : y;
		cin >> z;
		nRoads = max(nRoads, z);
		nPoints = max(nPoints, max(x, y));
		G[x][z] = y;
		G[y][z] = x;
		degree[x]++; 
		degree[y]++;

		while(scanf("%d%d", &x, &y) && x && y)
		{
			cin >> z;
			nRoads = max(nRoads, z);
			nPoints = max(nPoints, max(x, y));
			G[x][z] = y;
			G[y][z] = x;
			degree[x]++; 
			degree[y]++;
		}

		bool flag = true;
		for(int i = 1; i <= nPoints; i++)
			if(degree[i] & 1)
				flag = false;

		if(!flag)
			cout << "Round trip does not exist." << endl;
		else
		{
			euler(start, nRoads);
			printf("%d", stack[top]);
			for(int i = top - 1; i > 0; i--)
				printf(" %d", stack[i]);
			cout << endl;
		}
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值