通过这一题学习了欧拉路径和欧拉回路问题(即一笔画问题)的判定方法:
欧拉路径,即从一点出发到另一点结束且经过图中所有边的路径;欧拉回路,即从一点出发仍在这一点结束且经过图中所有边的路径。
对于无向图,存在欧拉路径,必须满足两个条件:
(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