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
| # 더 많은 정보는 42jerrykim.github.io 에서 확인하세요.
import sys
sys.setrecursionlimit(1_000_000)
input = sys.stdin.readline
def solve():
N, M = map(int, input().split())
edges = [None]*M
adj = [[] for _ in range(N+1)]
for i in range(M):
u, v = map(int, input().split())
edges[i] = (u, v)
adj[u].append((v, i))
adj[v].append((u, i))
def other(eid, v):
a, b = edges[eid]
return b if a == v else a
visV = [False]*(N+1)
visE = [False]*M
unpaired = [[] for _ in range(N+1)]
ans = []
stack = []
for s in range(1, N+1):
if visV[s]:
continue
stack.append([s, -1, -1, 0]) # v, parent, parentEdge, idx
while stack:
v, parent, parentEdge, idx = stack[-1]
if not visV[v]:
visV[v] = True
if idx < len(adj[v]):
u, eid = adj[v][idx]
stack[-1][3] += 1
if visE[eid]:
continue
visE[eid] = True
if not visV[u]:
stack.append([u, v, eid, 0])
else:
unpaired[v].append(eid)
else:
vec = unpaired[v]
while len(vec) >= 2:
e1 = vec.pop()
e2 = vec.pop()
u1 = other(e1, v)
u2 = other(e2, v)
ans.append((u1, v, u2))
if parent != -1:
if vec:
e1 = vec.pop()
u1 = other(e1, v)
ans.append((u1, v, parent))
else:
unpaired[parent].append(parentEdge)
stack.pop()
print(len(ans))
for u, v, w in ans:
print(u, v, w)
if __name__ == "__main__":
solve()
|