반응형
문제
https://www.acmicpc.net/problem/1005
풀이
import sys
from collections import deque
input = sys.stdin.readline
def solve():
n, k = map(int, input().split())
D = list(map(int,input().split()))
g = {}
memo = [0] * n
answerlist = [0] * n
for i in range(k):
x, y = map(int, input().split())
x -= 1
y -= 1
if x not in g:
g[x] = []
g[x].append(y)
memo[y] += 1
last = int(input())
last -= 1
queue = deque()
for i in range(n):
if memo[i] == 0:
queue.append(i)
answerlist[i] = D[i]
while queue:
cur = queue.popleft()
if cur in g:
for next in g[cur]:
memo[next] -= 1
answerlist[next] = max(answerlist[next], answerlist[cur] + D[next])
if memo[next] == 0:
queue.append(next)
print(answerlist[last])
t = int(input())
for i in range(t):
solve()
위상정렬을 이용한 풀이입니다.
memo 리스트의 각 노드의 진입차수를 기록하고 진입차수 0의 노드를 큐에 삽입합니다.
큐에서 노드를 하나씩 빼며 노드가 갈 수 있는 노드들의 진입 차수를 1씩 줄이며 max(answerlist[next], answerlist[cur] + D[next])을 기록합니다.
반응형
'Programming > 알고리즘' 카테고리의 다른 글
[백준/Python] 1647번 도시 분활 계획 (0) | 2025.03.02 |
---|---|
[백준/Python] 1644번 소수의 연속합 (0) | 2025.02.28 |
[백준/Python] 32986번 나는 건포도가 싫어요 (0) | 2025.01.18 |
[프로그래머즈/Python] 2022 블라인드 카카오 - 양궁대회 (0) | 2025.01.05 |
[백준/Python] 11758번 CCW (0) | 2025.01.02 |
댓글