programmers.co.kr/learn/courses/30/lessons/72416
ํ์คํ ์ด๋ ต๋ค์..
๊ฐ์ธ์ ์ผ๋ก 2021 ์นด์นด์ค ๋ฌธ์ ์ค ๊ฐ์ฅ ์ด๋ ค์ ๊ณ , ์๊ณ ๋ฆฌ์ฆ ๊ณต๋ถ๋ฅผ ์ด์ฌํ ํด์ผ๊ฒ ๋ค๊ณ ๋๊ผ๋ ๋ฌธ์ ์ ๋๋ค..
DP๋ฌธ์ ์ธ๋ฐ, ์๊ฐ๋ณด๋ค ๊ตฌํ๋ฐฉ๋ฒ์ด ์ ์๋ ์ฌ๋ผ ๋ต์์ ๋ณด์์ต๋๋ค.
์ฐ์ Root๋ 1๋ฒ์ด๋, 1๋ฒ๋ถํฐ ํ์์ ์์ํฉ๋๋ค.
์ผ์ด์ค๋ ๋๊ฐ์ง ์ ๋๋ค
1) dp[n][1] => n๋ฒ ์ฌ๋์ด ์ ๋ฐ๋๋ ๊ฒฝ์ฐ
2) dp[n][0] => n๋ฒ ์ฌ๋์ด ์ ๋ฐ๋์ง ์๋ ๊ฒฝ์ฐ
1๋ฒ ์ผ์ด์ค์ ๊ฒฝ์ฐ์๋ ์ฝ๊ฒ ์๊ฐํ ์ ์๋๋ฐ์. n๋ฒ์ ๋งค์ถ์ก์ ๋ํ๊ณ n๋ฒ์ ์์๋ค์ด ์ ๋ฐ์ด ๋๋ , ์๋๋ ์ต์๊ฐ๋ง ์ ํํ๋ฉด ๋ฉ๋๋ค.
2๋ฒ ์ผ์ด์ค์ ๊ฒฝ์ฐ ์กฐ๊ธ ๊น๋ค๋กญ์ต๋๋ค.
n๋ฒ์ ๋งค์ถ์ก์ ๋ํ์ง ์๊ณ , n๋ฒ์ ์์๋ค์ด ์ ๋ฐ์ด ๋๋ , ์๋๋ ์ต์๊ฐ๋ง์ ์ ํํ๋ฉด ๋ฉ๋๋ค.
ํ์ง๋ง, ๋ชจ๋ ์์๋ค์ด ์ ๋ฐ๋์ง ์๋ ์ผ์ด์ค๋ ์์ด์ผ ํฉ๋๋ค!
๊ทธ ๊ฒฝ์ฐ๋ฅผ flag๋ฅผ ์ฃผ์ด์ ์ฒ๋ฆฌํ์ต๋๋ค.
๋ง์ฝ ๋ชจ๋ ์์๋ค์ด ์ ๋ฐ๋์ง ์๋ ๊ฒฝ์ฐ๋ ๋ฐฉ๋ฌธํ ๊ฒฝ์ฐ์, ๋ฐฉ๋ฌธ์ ํ์ง ์์ ๊ฒฝ์ฐ์ ์ฐจ์ด๊ฐ์ด ๊ฐ์ฅ ์์ ๋
์์ ์ ํํด์ค๋๋ค.
์๋๋ฉด ๊ทธ ๊ฒฝ์ฐ๊ฐ ๋งค์ถ์ก ์ํด๊ฐ ๊ฐ์ฅ ์ ์ ๊ฒฝ์ฐ์ด๊ฑฐ๋ ์.
๋ง์ ํ๊ธฐ๋ ์ฌ์ด๋ฐ, ๋ง์ ์ฝ๋๋ฅผ ์ง๋ฉด ๋ ์ด๋ ค์ด ๋ฌธ์ ์์ต๋๋ค.
๊ทธ๋๋ ์ฝ๋๋ฅผ ๋ณด์๋ฉด ์ดํดํ์ค ์ ์์ผ์ค ๊ฒ์ ๋๋ค.
from copy import deepcopy
import sys
cost = None
dp = None
tree = None
INF = sys.maxsize
# n๋ฒ์ด ์ ๋ฐ๋๋ ๊ฒฝ์ฐ, ์๋๋ ๊ฒฝ์ฐ ๋ถ๊ธฐ ์ฒ๋ฆฌ
def dfs(n, include):
global cost, dp, tree
if dp[n][include] != -1:
return dp[n][include]
ret = 0
if include:
ret = cost[n]
for child in tree[n]:
c_cost = min(dfs(child, 0), dfs(child, 1))
ret += c_cost
# print(n, include, ret)
dp[n][include] = ret
return dp[n][include]
else:
# ๋ด๊ฐ ํฌํจ๋์ง ์์๋ค๋ฉด ํ์์ง์ ์ค ํ๋๋ ๋ฌด์กฐ๊ฑด ์์ด์ผ ํจ.
ans = 0
diff = 0 if len(tree[n]) == 0 else INF
# ์์์ด ๋ชจ๋ ์ฐธ์ฌ ์ํ๋ฉด, flag = False
flag = False
for child in tree[n]:
cost1 = dfs(child, 1)
cost2 = dfs(child, 0)
# ๋ฐฉ๋ฌธํ ์ฝ์คํธ๊ฐ ๋ฐฉ๋ฌธ์ํ ์ฝ์คํธ๋ณด๋ค ์๋ค => ์์ ์ค ๋ฐฉ๋ฌธํ ์ผ์ด์ค๊ฐ ์กด์ฌํจ์ ์๋ฏธ, flag = True
if cost1 < cost2:
flag = True
else:
diff = min(cost1 - cost2, diff)
ans += min(cost1, cost2)
ret = ans if flag else diff + ans
dp[n][include] = ret
return dp[n][include]
def solution(sales, links):
global dp, tree, cost
answer = 0
sales = [-1] + sales
cost = sales
tree = [[] for _ in range(len(sales))]
dp = [[-1, -1] for _ in range(len(sales))]
# dp[n][1] n๋ฒ์ด ์ ๋ฐ๋๋ ๊ฒฝ์ฐ
# dp[n][0] n๋ฒ์ด ์ ๋ฐ๋์ง ์๋ ๊ฒฝ์ฐ
for p, c in links:
tree[p].append(c)
return min(dfs(1,1), dfs(1, 0))
'Problem Solving ๐ฅ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] ๋ฌด์ง์ ๋จน๋ฐฉ ๋ผ์ด๋ธ / ์ฐ์ ์์ ํ(ํ) (0) | 2021.05.03 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค / 2018 KAKAO ์๋์์ฑ / ํ์ด์ฌ / ํธ๋ผ์ด (0) | 2021.05.03 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์คํจ์จ / Python (0) | 2021.04.07 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์์ ๊ฒ์ / Python (0) | 2021.04.06 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ฟ ํค ๊ตฌ์ / ํ์ด์ฌ (0) | 2021.02.22 |