UVa 10054 The Necklace

链接

传送门

题意

给出\(n\)条边,求是否有欧拉回路,如果有就输出。

思路

连通且所有结点度数均为偶数即有欧拉回路。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;

typedef long long LL;
const int maxn = 55;
int d[maxn], g[maxn][maxn];
bool vis[maxn];

int dfs1(int u) {
vis[u] = true;
int res = 1;
for (int i = 0; i < maxn; ++i) {
if (!vis[i] && g[u][i]) {
res += dfs1(i);
}
}
return res;
}

void dfs2(int u) {
for (int i = 0; i < maxn; ++i) {
if (g[u][i] > 0) {
--g[u][i], --g[i][u];
dfs2(i);
printf("%d %d\n", i, u);
}
}
}

int main() {
int t, tt = 0;
scanf("%d", &t);
while (t--) {
if (tt) {
puts("");
}
memset(d, 0, sizeof d);
memset(g, 0, sizeof g);
memset(vis, 0, sizeof vis);
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
int u, v;
scanf("%d%d", &u, &v);
g[u][v]++, g[v][u]++;
++d[u], ++d[v];
}
bool ok = true;
int num = 0, root = -1;
for (int i = 1; i < maxn; ++i) {
if (d[i]) {
root = i;
++num;
if (d[i] & 1) {
ok = false;
break;
}
}
}
if (ok && dfs1(root) != num) {
ok = false;
}
printf("Case #%d\n", ++tt);
if (!ok) {
puts("some beads may be lost");
} else {
dfs2(root);
}
}
return 0;
}