https://school.programmers.co.kr/learn/courses/30/lessons/86971
ํ๋ก๊ทธ๋๋จธ์ค
SW๊ฐ๋ฐ์๋ฅผ ์ํ ํ๊ฐ, ๊ต์ก์ Total Solution์ ์ ๊ณตํ๋ ๊ฐ๋ฐ์ ์ฑ์ฅ์ ์ํ ๋ฒ ์ด์ค์บ ํ
programmers.co.kr
2026.04.01
์๋ฆฐ๊ฑฐ ๊ณ ๋ คํ๋๊ฑธ ๊ทธ๋ฅ cut_a, cut_b๋ก ํ๋ฉด ๊ฐ๋จํ์
def dfs(curr, graph, visited, cut_a, cut_b):
visited[curr] = True
cnt = 1
for g in graph[curr]:
if (curr == cut_a and g == cut_b) or (curr == cut_b and g == cut_a):
continue
if not visited[g]:
cnt += dfs(g, graph, visited, cut_a, cut_b)
return cnt
def solution(n, wires):
graph = [[] for _ in range(n+1)]
for w in wires:
a, b = w
graph[a].append(b); graph[b].append(a)
diff = []
for w in wires:
cut_a, cut_b = w
visited = [False] * (n+1)
cut1 = dfs(cut_a, graph, visited, cut_a, cut_b)
cut2 = n - cut1
diff.append(abs(cut1-cut2))
return min(diff)
์ฐ๊ฒฐ๋ ๊ฐ์ ์ ๋, ์ ์ญ๋ณ์๋ฅผ ์ฌ์ฉํ์ง ์๋๋ค๋ฉด cnt += dfs๋ฅผ ์ฌ์ฉํ ๊ฒ
๊ทธ๋ํ ๋ง๋ค์ด์ ์ ๊ทผํ๋๊ฑด ์ํ์
def dfs(wires, graph, curr, no_wire_idx, visited):
cnt = 1
visited[curr] = True
for next in graph[curr]:
if not visited[next]:
if curr and next not in wires[no_wire_idx]:
cnt += dfs(wires, graph, next, no_wire_idx, visited)
return cnt
def solution(n, wires):
# graph ๋ง๋ค๊ธฐ
graph = [[] for _ in range(n+1)]
for i in range(len(wires)):
a, b = wires[i]
graph[a].append(b); graph[b].append(a)
result_list = set()
# ๋ชจ๋ ์ ์ ์ ๋ํ์ฌ ํ๋ฒ์ฉ ์งํ
for i in range(len(wires)):
a, b = wires[i]
visited = [False] * (n+1)
group1 = dfs(wires, graph, a, i, visited)
group2 = n - group1
result_list.add(group1-group2 if group1>group2 else group2-group1)
return min(result_list)'๐ Study > Baekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Silver IV] 2578 ๋น๊ณ (0) | 2026.03.31 |
|---|---|
| ํ๋ก๊ทธ๋๋จธ์ค Lv2 | ์์ ํ์ | ๋ชจ์์ฌ์ (0) | 2025.10.11 |
| ํ๋ก๊ทธ๋๋จธ์ค Lv2 | ์์ ํ์ | ํผ๋ก๋ (0) | 2025.10.11 |
| ํ๋ก๊ทธ๋๋จธ์ค Lv2 | ์์ ํ์ | ์นดํซ (0) | 2025.10.11 |
| ํ๋ก๊ทธ๋๋จธ์ค Lv2 | ์์ ํ์ | ์์ ์ฐพ๊ธฐ (0) | 2025.10.11 |