Skip to content

Commit 35b832e

Browse files
committed
트리 풀이
1 parent 1e05512 commit 35b832e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

BAEKJOON/3Gold/트리.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# 자료 구조, 그래프 이론, 그래프 탐색, 트리, 깊이 우선 탐색, 분리 집합
2+
# https://www.acmicpc.net/problem/4803
3+
4+
import sys
5+
from collections import deque
6+
7+
input = sys.stdin.readline
8+
9+
def dfs(start, graph, visit):
10+
stack = deque([(start)])
11+
is_not_cycle = True
12+
while stack:
13+
node = stack.pop()
14+
if visit[node]:
15+
is_not_cycle = False
16+
continue
17+
18+
visit[node] = True
19+
20+
for nxt in graph[node]:
21+
if not visit[nxt]:
22+
stack.append((nxt))
23+
24+
return is_not_cycle
25+
26+
tc = 0
27+
tc_answer = []
28+
while True:
29+
N,M = map(int, input().split())
30+
if N == M == 0:
31+
break
32+
33+
tc += 1
34+
visit = [False]*(N+1)
35+
graph = [[] for _ in range(N+1)]
36+
for _ in range(M):
37+
a,b = map(int, input().split())
38+
graph[a].append(b)
39+
graph[b].append(a)
40+
41+
answer = 0
42+
for n in range(1, N+1):
43+
if not visit[n] and dfs(n, graph, visit):
44+
answer += 1
45+
46+
print_answer = f"Case {tc}: "
47+
if answer == 0:
48+
print_answer += "No trees."
49+
elif answer == 1:
50+
print_answer += "There is one tree."
51+
else:
52+
print_answer += f"A forest of {answer} trees."
53+
54+
tc_answer.append(print_answer)
55+
56+
print("\n".join(tc_answer))

0 commit comments

Comments
 (0)