【模板】欧拉回路
LJY_ljy
·
·
算法·理论
欧拉回路模板:
e.g
P2731 [USACO3.3]骑马修栅栏 Riding the Fences
P6066 [USACO05JAN]Watchcow S
///无向图中的欧拉回路
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 50010
using namespace std;
inline int read() {
register int x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
int N, M, head[MAXN << 1];
struct node {
int to, next;
} E[MAXN << 1];
int sta[MAXN << 1], ans[MAXN << 1], top, eid = 1; ///手动模拟栈,避免栈溢出
int cnt;
bool vis[MAXN << 1];
inline void addedge(int x, int y) {
E[++eid].to = y;
E[eid].next = head[x];
head[x] = eid;
}
inline void Euler() {
sta[++top] = 1;
while (top) {
int x = sta[top], i = head[x];
while (i & vis[i]) i = E[i].next;
if (i) {
sta[++top] = E[i].to;
vis[i] = vis[i ^ 1] = true; ///无向图存储中的成对变换,但初始的eid必须是1(第一条边是2)
head[x] = E[i].next;
} else {
top--;
ans[++cnt] = x;
}
}
}
int main() {
N = read(); M = read();
for (int i = 1; i <= M; i++) {
int x = read(), y = read();
addedge(x, y);
addedge(y, x);
}
Euler();
for (int i = cnt; i; i--)
printf("%d\n", ans[i]);
return 0;
}