POJ-3360(欧拉路径和欧拉回路)

通过这一题学习了欧拉路径和欧拉回路问题(即一笔画问题)的判定方法:

欧拉路径,即从一点出发到另一点结束且经过图中所有边的路径;欧拉回路,即从一点出发仍在这一点结束且经过图中所有边的路径。

对于无向图,存在欧拉路径,必须满足两个条件:

(1)不算孤立点的图连通

(2)除起点和终点的度为奇数外,图中其他点的度数均为偶数

存在欧拉回路的条件也有两个:

(1)不算孤立点的图连通

(2)所有点的度数均为偶数

需要注意的是,欧拉路径和欧拉回路关注的是经过所有边,因此孤立点并不起作用。

#include <cstdio>
#include <cctype>
#include <cstring>

enum Type{Plain, EulerPath, EulerCycle};

bool used[52];
int  map[128], degree[52], father[52];
int Find(int x){
	return x != father[x] ?  father[x] = Find(father[x]) : x;
}
void Union(char x, char y)
{
	int a = map[x], b = map[y];
	++degree[a];
	++degree[b];
	father[Find(b)] = Find(a);
}
void init()
{
	int i = 0;
	for(char c = 'a'; c <= 'z'; ++c) map[c] = i++;
	for(char c = 'A'; c <= 'Z'; ++c) map[c] = i++;
}
void reset()
{
	memset(used, 0, sizeof(used));
	memset(degree, 0, sizeof(degree));
	for(int i = 0; i < 52; ++i) father[i] = i;
}
bool inputVertex()
{
	int c;
	while(c = getchar(), c != -1){
		if(c == '{') break;
	}
	if(c == -1) return false;
	while(c = getchar(), c != '}'){
		if(isspace(c) || c == ',') continue;
		used[map[c]] = true;
	}
	return true;
}
void inputEdge()
{
	char c, x, y;
	while(c = getchar(), c != '}'){
		if(c == '('){
			x = getchar();
			getchar();
			y = getchar();
			Union(x, y);
		}
	}
}
bool isConnected()
{
	bool flag = false;
	for(int i = 0; i < 52; ++i){
		if(used[i] && degree[i] && Find(i) == i){//do not count isolate vertex
			flag = !flag;
			if(!flag) break;
		}
	}
	return flag;
}
int getType()
{
	int odd = 0;
	for(int i = 0; i < 52; ++i){
		if(used[i] && (degree[i] & 1)) ++odd;
	}
	if(odd == 0) return EulerCycle;
	if(odd == 2) return EulerPath;
	return Plain;
}

int main()
{
	init();
	while(true){
		reset();
		if(!inputVertex()) break;
		inputEdge();
		if(!isConnected()) puts("No No");
		else{
			switch(getType()){
				case Plain: 	puts("No No"); 	break;
				case EulerPath:	puts("Yes No"); break;
				default:	puts("No Yes"); break;
			}
		}
	}
	return 0;	
}
找到一篇写找欧拉路径/回路的算法,好写,易懂: http://blog.csdn.net/supersnow0622/article/details/10461985

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值