欧拉路问题
本次比赛的水题
对于这题的无向图,要每一个点的度数都为偶数,才存在欧拉回路。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int G[50][2000]; //G[点][边] = 点
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)
{
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(cin>>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(cin>>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] %2)
flag = false;
if(!flag)
cout << "Round trip does not exist." << endl;
else
{
euler(start, nRoads);
cout<<stack[top];
for(int i = top - 1; i > 0; i--)
cout<<" "<<stack[i];
cout << endl;
}
}
return 0;
}