Skip to content

Commit 11fecba

Browse files
authored
有向图的欧拉回路
1 parent 9ec1c2e commit 11fecba

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed

Eulerian-Tour(Digraph).cpp

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#include <cstdio>
2+
3+
#define NIL 0
4+
5+
using namespace std;
6+
7+
struct vertex
8+
{
9+
int first, ideg, odeg;
10+
bool vis;
11+
}V[100010];
12+
13+
struct edge
14+
{
15+
int op, endp, next;
16+
}E[200010];
17+
18+
int ec = 1, ivc, iec, cnt = 0;
19+
int path[200010], pc;
20+
21+
void add_edge(int u, int v)
22+
{
23+
V[u].odeg++;
24+
V[v].ideg++;
25+
E[ec].next = V[u].first;
26+
V[u].first = ec;
27+
E[ec].op = u;
28+
E[ec].endp = v;
29+
ec++;
30+
}
31+
32+
void del_edge(int ord)
33+
{
34+
V[E[ord].op].first = E[ord].next;
35+
}
36+
37+
void connect(int u)
38+
{
39+
if (V[u].vis == false)
40+
{
41+
cnt++;
42+
V[u].vis = true;
43+
for (int cur = V[u].first; cur != 0; cur = E[cur].next)
44+
{
45+
connect(E[cur].endp);
46+
}
47+
}
48+
}
49+
50+
void DFS(int u, int start)
51+
{
52+
int first = V[u].first;
53+
del_edge(first);
54+
if (E[first].endp != start)
55+
{
56+
DFS(E[first].endp, start);
57+
}
58+
path[pc++] = first;
59+
while (V[u].first != NIL)
60+
{
61+
DFS(u, u);
62+
}
63+
}
64+
65+
int main()
66+
{
67+
int k, u, v;
68+
scanf("%d%d%d", &k, &ivc, &iec);
69+
for (int i = 0; i < iec; i++)
70+
{
71+
scanf("%d%d", &u, &v);
72+
add_edge(u, v);
73+
}
74+
for (int i = 1; i <= ivc; i++)
75+
{
76+
if (V[i].ideg != V[i].odeg)
77+
{
78+
printf("NO");
79+
return 0;
80+
}
81+
if (V[i].ideg == 0)
82+
{
83+
cnt++;
84+
}
85+
}
86+
int vhe;
87+
for (int i = 1; i <= ivc; i++)
88+
{
89+
if (V[i].ideg != 0)
90+
{
91+
connect(i);
92+
vhe = i;
93+
break;
94+
}
95+
}
96+
if (cnt < ivc)
97+
{
98+
printf("NO");
99+
return 0;
100+
}
101+
printf("YES\n");
102+
if (iec == 0)
103+
{
104+
return 0;
105+
}
106+
DFS(vhe, vhe);
107+
for (int i = pc - 1; i >= 0; i--)
108+
{
109+
printf("%d ", path[i]);
110+
}
111+
return 0;
112+
}

0 commit comments

Comments
 (0)