就是欧拉判定,判定之后就可以使用DFS求欧拉回路了。图论内容。
这里使用邻接矩阵会快很多速度。
这类题目都是十分困难的,光是定义的记录的数组变量就会是一大堆。
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>
using namespace std;
struct Edge
{
int ed, des;
Edge(int e = 0, int d = 0) : ed(e), des(d) {}
};
const int EDGES = 2000;//1996;
const int VEC = 45;
stack<int> stk;
int degree[VEC];
vector<Edge> gra[VEC];
bool vis[EDGES];
void euler(int u)
{
for(int i = 0; i < (int)gra[u].size(); i++)
{
if(!vis[gra[u][i].ed]) //标志访问过了,这里需要表示桥,不是顶点
{
vis[gra[u][i].ed] = true;
euler(gra[u][i].des);
stk.push(gra[u][i].ed);
//不能break
}
}
}
int main()
{
int x, y, z, one;
while (scanf("%d %d", &x, &y) != EOF && x && y)
{
memset(vis, 0, sizeof(vis));
memset(degree, 0, sizeof(degree));
for (int i = 1; i < VEC; i++)
gra[i].clear();
scanf("%d", &z);
one = min(x, y);
degree[x]++; degree[y]++;
gra[x].push_back(Edge(z, y)); gra[y].push_back(Edge(z, x));
while (scanf("%d %d", &x, &y) != EOF && x && y)
{
scanf("%d", &z);
gra[x].push_back(Edge(z, y)); gra[y].push_back(Edge(z, x));
degree[x]++, degree[y]++;
}
for (int i = 1; i < VEC; i++)
{
if (degree[i] & 1)
{
puts("Round trip does not exist.");
goto endLoop; //玩玩goto
}
}
euler(one);
while (!stk.empty())
{
printf("%d ", stk.top());
stk.pop();
}
putchar('\n');
endLoop:;
}
return 0;
}