题解 UVA10735 【混合图的欧拉回路 Euler Circuit】
由于有向图有欧拉回路当且仅当图是弱连通的并且所有点的 入度-出度=0,可以发现关键问题在于如何给无向边定向使得入度-出度=0.
先给所有无向边任意指定一个方向,并令 d'[i]=i的出度-入度(算上原图的有向边和定向了的无向边)。
如果某个 d'[i] 是奇数(相当于说它连接了奇数条边,包括有向边和无向边),那么显然无解,否则令 d[i]=d'[i]/2(为了方便,暂时称其为“度”)。
考虑如果有一条边 u->v 在原图中是无向边,那么将它反向,变成 v->u 之后,u的出度-1,入度+1,从而 d[u]-=1;同理,d[v]+=1.
可以发现这相当于说把 u 的一个度“流到”了 v 的一个度。 于是我们(在网络流中)从 u 到 v 连一条容量为 1 的边,表示可以在 d[u] 中流出一个给 d[v]。
另外,对每个点 u,如果 d[u]>0,那么要从 S 到 u 连一条容量为 d[u] 的边,表示 u 这里多出了 d[u] 的度; 否则 d[u]<=0,就从 u 到 T 连一条容量为 -d[u] 的边,表示 u 这里缺少 -d[u] 的度。
执行一遍最大流之后如果 S 出发的所有弧都满流,就说明所有多出来的度都流出去了(同时所有少的度都补上了,因为少的度的总数
这时候只需要看网络流中哪些 u->v 的边流上了,就知道哪些边需要反向。把这些边反向之后找一遍有向图欧拉回路即可。
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <vector>
typedef long long LL;
int readInt() {
int ans = 0, c, f = 1;
while (!isdigit(c = getchar()))
if (c == '-') f *= -1;
do ans = ans * 10 + c - '0';
while (isdigit(c = getchar()));
return ans * f;
}
const int N = 105;
const int M = 1500;
int n, m, S, T, pre[N], nxt[M], to[M], ret[M], d[N], cnt, sum;
int u[M], v[M], id[M];
std::vector<int> V[N];
inline void addEdge(int x, int y, int r) {
nxt[cnt] = pre[x];
ret[cnt] = r;
to[pre[x] = cnt++] = y;
nxt[cnt] = pre[y];
ret[cnt] = 0;
to[pre[y] = cnt++] = x;
}
bool Init() {
n = readInt(); m = readInt();
S = 0; T = n + 1;
memset(pre, -1, sizeof pre);
cnt = 0;
memset(d, 0, sizeof d);
for (int i = 0; i < m; ++i) {
u[i] = readInt(); v[i] = readInt();
int c;
while (!isalpha(c = getchar()));
++d[u[i]]; --d[v[i]];
if (c == 'U') id[i] = cnt, addEdge(u[i], v[i], 1);
else id[i] = -1;
}
sum = 0;
for (int i = 1; i <= n; ++i) {
if (d[i] & 1) return false;
d[i] /= 2;
if (d[i] > 0) {
addEdge(S, i, d[i]);
sum += d[i];
} else addEdge(i, T, -d[i]);
}
return true;
}
int que[N], dis[N], cur[N];
bool BFS() {
int hd = 0, tl = 0;
memset(dis, -1, sizeof dis);
dis[que[tl++] = S] = 0;
while (hd < tl)
for (int x = que[hd++], i = pre[x]; ~i; i = nxt[i])
if (ret[i] != 0 && dis[to[i]] == -1)
dis[que[tl++] = to[i]] = dis[x] + 1;
return dis[T] != -1;
}
int DFS(int x, int maxf) {
if (x == T) return maxf;
int ans = 0;
for (int &i = cur[x]; ~i; i = nxt[i])
if (ret[i] != 0 && dis[to[i]] == dis[x] + 1) {
int t = DFS(to[i], std::min(ret[i], maxf - ans));
ret[i] -= t;
ret[i ^ 1] += t;
if ((ans += t) == maxf) break;
}
return ans;
}
void Euler(int x) {
while (!V[x].empty()) {
int y = V[x].back(); V[x].pop_back();
Euler(y);
printf(" %d", x);
}
}
void Solve() {
int ans = 0;
while (BFS())
memcpy(cur, pre, sizeof cur), ans += DFS(S, 0x7fffffff);
if (ans != sum) puts("No euler circuit exist");
else {
for (int i = 1; i <= n; ++i) V[i].clear();
for (int i = 0; i < m; ++i)
if (id[i] >= 0 && !ret[id[i]])
V[u[i]].push_back(v[i]);
else
V[v[i]].push_back(u[i]);
printf("1");
Euler(1);
puts("");
}
}
int main() {
int T = readInt();
while (T--) {
if (!Init()) puts("No euler circuit exist");
else Solve();
if (T) puts("");
}
return 0;
}