๋ฑ๋ lv3
๐๋ฌธ์ ๋งํฌ
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
import sys
from collections import defaultdict
sys.setrecursionlimit(100000)
A = defaultdict(list)
vis = [False] * 100000
def dfs(node):
vis[node] = True
if not A[node]:
return 1, 0
on, off = 1, 0
for v in [v for v in A[node] if not vis[v]]:
leaf_on, leaf_off = dfs(v)
on += min(leaf_on, leaf_off)
off += leaf_on
return leaf_on, leaf_off
def solution(n, lighthouse):
for node, v in lighthouse:
A[node].append(v)
A[v].append(node)
on, off = dfs(1)
return min(on, off)
ํด์ค
1
2
sys.setrecursionlimit(100000)
# ์ฌ๊ทํจ์๋ 1000~3000๋ฒ ๋ฐ๋ณต์ธ๋ฐ ๋๋์ก์ 10๋ง๋ฒ์ผ๋ก ๋๋ ค์ค
1
2
3
4
5
def dfs(node): # ์์๋
ธ๋์ธ node๋ฅผ ๋ฐ์ ํด๋น๋
ธ๋์์ ์ถ๋ฐํด DFS ์ํ
vis[node] = True
if not A[node]: # node๊ฐ ์์๋
ธ๋๋ผ๋ฉด node๊ฐ ์ผ์ง ์ํ๋ก ์ต์ ์ ๋ฑ ๋ฑ๋ 1๊ฐ, ๊บผ์ก์ ๋ 0๊ฐ ๋ฐํ
return 1, 0
1
2
3
4
5
6
7
8
# ๋ด๊ฐ ๋ถ๋ชจ๋
ธ๋๋ผ๋ฉด
on, off = 1, 0
for v in [v for v in A[node] if not vis[v]]:
leaf_on, leaf_off = dfs(v)
on += min(leaf_on, leaf_off)
off += leaf_on
return on, off
1
2
3
4
5
6
7
8
9
10
#---------------- ๊ณตํต์ ๋ฐ ์ฐจ์ด -----------------
๊ณตํต์ : A[u]์์ vis[v]๊ฐ False์ธ ๋
ธ๋๋ค์ ๋ํด์๋ง ๋ฐ๋ณต
์ฐจ์ด
for v in [v for v in A[node] if not vis[v]]:
# ์๋ก์ด ๋ฆฌ์คํธ๋ก ๋ง๋ค์ด ์ํ
v for v in A[node] if not vis[v]:
# (๋ฆฌ์คํธ ์๋ง๋ฆ) v์ฉ ์ปค์ง๋ฉฐ ๊ฐ v๋ง๋ค ์ํํ๋ค ๋ฐฉ๋ฌธํ์ง ์์ ๊ณณ์
1
2
3
4
A[node].append(v) # ๋ถ๋ชจ๋
ธ๋์ ๋ฐฉ๋ฌธํ ๋ฆฌํ๋
ธ๋ ์ถ๊ฐ
A[v].append(node) # ๋ฐฉ๋ฌธํ ๋ฆฌํ๋
ธ๋์ ๋ถ๋ชจ๋
ธ๋ ์ฐ๊ฒฐ
on, off = dfs(1) # 1๋ถํฐ ํ์ ์์
์ฐธ๊ณ
This post is licensed under CC BY 4.0 by the author.