欧拉通路/回路模版

Fleury算法定义

Code:

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
76
77
78
79
80
81
82
83
84
85
86
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a; i<=b; ++i)
#define per(i,b,a) for(int i=b; i>=a; --i)
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ms(a, b) memset(a, b, sizeof(a))
#define de(a) cout <<#a <<" => "<<a<<endl
#define dep(a, b) cout <<"("<<a<<","<<b<<")"<<endl
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int>vi;
typedef vector<pii>vpi;
const int maxn = 1e5+7;
vpi edge[maxn];
vi ans;
void adde(int u, int v, int id){
edge[u].pb(mp(v, id));
edge[v].pb(mp(u, id));
return ;
}
stack<int>stk;
bool vis[maxn];
void dfs(int u) {
stk.push(u);
int size=edge[u].size()-1;
while((int)edge[u].size()!=0) {
pii e = edge[u].back();
edge[u].pop_back();
if(vis[e.se]) continue;
vis[e.se] = true;
dfs(e.fi);
break;
}
return ;
}
void fleury(int u) {
stk.push(u);
while(!stk.empty()){
int v = stk.top();
stk.pop();
if((int)edge[v].size() != 0) dfs(v);
else ans.pb(v);
}
int size=ans.size()-1;
rep(i, 0, size-1){
printf("%d -> %d\n", ans[i], ans[i+1]);
}
return ;
}
int main(){
//freopen("in.txt", "r", stdin);
ms(vis, false);
int n, m, u, v;
scanf("%d%d", &n, &m);
rep(i, 1, m) {
scanf("%d%d", &u, &v);
adde(u, v, i);
}
int st=1;
int sum = 0;
rep(i, 1, n) {
if((int)edge[i].size()%2) {
st = i;
sum++;
}
}
if(sum == 0 ) puts("不存在欧拉通路");
else fleury(st);
return 0;
}
/*
9 10
1 9
1 5
5 3
3 2
2 4
4 5
9 8
8 7
7 6
6 8
*/