这个题目和POJ 1086不同,1086是有向图欧拉回路,这个是无向图欧拉回路。还有一个很重要的一点,本题目事先声明是连通图,所以不需要进行图遍历验证连通性。剩下的就是判断是否存在欧拉路,然后进行输出。
本题目不要求字典序,但是本代码是按照字典序输出的。
下面是关于七桥问题以及欧拉路的百度百科,不清楚的朋友可以看看:http://baike.baidu.com/view/142962.htm, 个人认为还是讲的比较清楚。
下面是代码:
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#define M 50
using namespace std;
struct edge { int a,b,c; };
struct T { int b,c; };
int n, sum[M], st, path[1997], q;
edge dis[1997];
bool v[1997];
vector<T> e[M];
void eulerpath( int s )
{
for ( int i = 0; i < e[s].size(); i++ )
if ( !v[e[s][i].c] )
{
v[e[s][i].c] = true;
eulerpath(e[s][i].b);
path[q++] = e[s][i].c;
}
}
bool cmp( edge a, edge b)
{
return a.c < b.c;
}
int main()
{
int i, j, k, a, b, c, t;
T w;
freopen( "ex.in", "r", stdin);
while ( scanf("%d%d", &a, &b) )
{
if ( a == 0 ) break;
t = 0; memset(sum,0,sizeof(sum));
while ( scanf("%d", &c) )
{
dis[t].a = --a; dis[t].b = --b; dis[t++].c = c;
sum[a]++; sum[b]++;
if ( t == 1 ) st = min(a,b);
scanf("%d%d", &a, &b);
if ( a == 0 ) break;
}
for ( i = 0; i < 44; i++ )
if ( sum[i] % 2 )
{
printf( "Round trip does not exist.\n");
break;
}
if ( i < 44 ) continue;
for ( i = 0; i < 44; i++ )
e[i].clear();
sort(dis,dis+t,cmp);
for ( i = 0; i < t; i++ )
{
w.b = dis[i].b; w.c = dis[i].c;
e[dis[i].a].push_back(w);
w.b = dis[i].a; w.c = dis[i].c;
e[dis[i].b].push_back(w);
}
q = 0;
memset(v,0,sizeof(v));
eulerpath(st);
printf( "%d", path[t-1]);
for ( i = t-2; i >= 0 ; i-- )
printf(" %d", path[i]);
printf( "\n" );
}
}