经典的欧拉回路题
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;
}