๐ ์์์ ๋ ฌ์ด๋?
์ด๋ค ์ผ์ ํ๊ธฐ ์ํด ์ผ๋ จ์ ์์
์ ์ฐจ๋ก๋๋ก ์ํํด์ผ ํ๋ ์๊ณ ๋ฆฌ์ฆ์ด๋ค.
์ฆ, B๋ฅผ ํ๊ธฐ ์ํด์ A๋ฅผ ํด์ผํ๊ณ , C๋ฅผ ํ๊ธฐ ์ํด์ B๋ฅผ ํด์ผํ๋ ์ํฉ์์ A-> B-> C ์์๋ก ํ ์ ์๋ค.
์๋ฅผ ๋ค์ด, ๋ํ๊ต์์ ์ ์ ๊ณผ๋ชฉ์ ๋ค์ด์ผ ํด๋น ๊ณผ๋ชฉ์ ๋ค์ ์ ์๋ฏ์ด ์์๊ฐ ์ ํด์ ธ ์๋ ์๊ณ ๋ฆฌ์ฆ์ด๋ค.
N(๋ ธ๋์ ๊ฐ์) = 5, M(๊ฐ์ ์ ๊ฐ์) = 5 ์ธ ๋ค์๊ณผ ๊ฐ์ ๊ทธ๋ํ์์ ์์์ ๋ ฌ์ ์ํํด๋ณด์.
์ด ์๊ณ ๋ฆฌ์ฆ์ ํด๊ฒฐํ๊ธฐ ์ํด์๋ 3๊ฐ์ง๋ฅผ ๊ณ ๋ คํด์ผ ํ๋ค.
- indegree
- queue
- graph
โ๏ธindegree
๊ฐ ๋ ธ๋์์ ์ง์ ์ฐจ์ ๊ฐ์๋ฅผ ์ ์ฅ
โ๏ธgraph
๋ ธ๋์ ์ธ์ ๋ฆฌ์คํธ๋ก ๊ทธ๋ํ ๊ตฌํ
โ๏ธqueue
1. popleft()ํด์ ๋์จ ๋ ธ๋์ ์ํฅ์ด ์๋ graph์ผ๋ก
2. ๋์จ ๋ ธ๋๋ฅผ indegree-=1
3. indegree ์ง์ ์ฐจ์๊ฐ 0์ด๋ฉด queue์ append() ํ๋ค.
indegree
[1] | [2] | [3] | [4] | [5] |
0 | 1 | 1 | 2 | 1 |
graph
[1] | [2] | [3] | [4] | [5] |
[2,3,4] | [4,5] |
1๏ธโฃ ๋ ธ๋ 1๋ถํฐ ์์
queue
[0] |
1 |
(1) queue.popleft() ํ๋ฉด 1์ด ๋์ค๋ฏ๋ก,
(2) graph์ index 1์ ์๋ [2,3,4]์ ํด๋นํ๋ indegree์์ -1๋ฅผ ํด์ค๋ค.
indegree
[1] | [2] | [3] | [4] | [5] |
0 | 0 | 0 | 1 | 1 |
(3) indegree [2,3,4] ์ค์์ ์ง์
์ฐจ์๊ฐ 0์ด๋ฉด queue์ ๋ฃ๋๋ค.
โผ๏ธ 4๋ 0์ด ์๋๋ฏ๋ก ์๋ต !!
queue
[0] | [1] |
2 | 3 |
2๏ธโฃ ๋ค์์ 2
(1) queue.popleft() ํ๋ฉด 2์ด ๋์ค๋ฏ๋ก,
(2) graph์ index 2์๋ ์๋ฌด๊ฒ๋ ์์ผ๋ ์๋ต.
indegree
[1] | [2] | [3] | [4] | [5] |
0 | 0 | 0 | 1 | 1 |
degree
[0] |
3 |
3๏ธโฃ ๋ค์์ 3
(1) queue.popleft() ํ๋ฉด 3์ด ๋์ค๋ฏ๋ก,
(2) graph์ index 1์ ์๋ [4,5]์ ํด๋นํ๋ indegree์์ -1๋ฅผ ํด์ค๋ค.
indegree
[1] | [2] | [3] | [4] | [5] |
0 | 0 | 0 | 0 | 0 |
(3) indegree [2,3,4] ์ค์์ ์ง์
์ฐจ์๊ฐ 0์ด๋ฉด queue์ ๋ฃ๋๋ค.
queue
[0] | [1] |
4 | 5 |
.
.
์ดํ.. ๋๊ฐ๋ค!
๐พ ๊ฒ์ ๊ฐ๋ฐํ๊ธฐ - ๋ฐฑ์ค 1516๋ฒ
https://www.acmicpc.net/problem/1516
์์ ์ ๋ ฅ1
5
10 -1
10 1 -1
4 1 -1
4 3 1 -1
3 3 -1
์์ ์ถ๋ ฅ1
10
20
14
18
17
๐ํ์ด
์์ ์ ๋ ฌ๋ก ๊ฑด๋ฌผ์ ์ง๋, ๊ฑด๋ฌผ์ ์ง๋ ์๊ฐ๋ ์ ์ฅํ๊ณ ์์ด์ผ ํ๋ค.
์๊ฐ ์
๋ฐ์ดํธ๋ฅผ ํด์ค์ผ ํ๋๋ฐ, ๋ค์ ๊ฑด๋ฌผ์ result์ ์๋ ๊ฐ๊ณผ ์ง๊ธ ๊ฑด๋ฌผ์ result๊ฐ๊ณผ ์ง๊ธ ๊ฑด๋ฌผ์ ์ง๋ ์๊ฐ์ ๋ํ ๊ฐ๊ณผ ๋น๊ต๋ฅผ ํด์ ๋ ํฐ ๊ฒ์ ์ ์ฅํ๋ค.
๐์ฝ๋
# ์์ ์ ๋ ฌ
from collections import deque
N = int(input())
building = [[] for _ in range(N + 1)]
cost = [0] * (N + 1)
indegree = [0] * (N + 1)
for i in range(1, N + 1):
inputList = list(map(int, input().split(' ')))[:-1]
cost[i] = inputList[0]
for j in range(1, len(inputList)):
building[inputList[j]].append(i)
indegree[i] += 1
# print(building)
# print(cost)
# print(indegree)
queue = deque()
for i in range(1, N + 1):
if indegree[i] == 0: # ์ ์ฝ์ด ์์ผ๋ฉด
queue.append(i)
result = [0] * (N + 1)
while queue:
now = queue.popleft()
for next in building[now]:
indegree[next] -= 1
# ์๊ฐ ์
๋ฐ์ดํธ
result[next] = max(result[next], result[now] + cost[now])
if indegree[next] == 0:
queue.append(next)
# print("result", result)
for i in range(1, N + 1):
print(result[i] + cost[i])
'Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์ค ์ธ์ฐ๊ธฐ] ์์ ์ ๋ ฌ | ๋ฐฑ์ค 2252๋ฒ | python (5) | 2024.09.01 |
---|---|
[๋ฏธ๋ก ํ์ถ] DFS&BFS | ์ด๊ฒ์ด ์ฝ๋ฉ์ด๋ค | python (0) | 2024.08.31 |
[K๋ฒ์งธ ์ต๋จ๊ฒฝ๋ก ์ฐพ๊ธฐ] ๋ค์ต์คํธ๋ผ | ๋ฐฑ์ค 1854๋ฒ | python (0) | 2024.08.30 |
[์๊ณ ๋ฆฌ์ฆ] ์ฐ์ ์์ ํ (0) | 2024.07.08 |
[์ต๋จ๊ฒฝ๋ก] ๋ค์ต์คํธ๋ผ | ๋ฐฑ์ค 1753๋ฒ | python (0) | 2024.07.07 |