728x90
https://www.acmicpc.net/problem/10282
10282번: 해킹
최흉최악의 해커 yum3이 네트워크 시설의 한 컴퓨터를 해킹했다! 이제 서로에 의존하는 컴퓨터들은 점차 하나둘 전염되기 시작한다. 어떤 컴퓨터 a가 다른 컴퓨터 b에 의존한다면, b가 감염되면
www.acmicpc.net
최종 노드까지 걸리는 시간을 구하는 문제이므로 다익스트라 알고리즘을 통해 풀 수 있었습니다.
from collections import deque
import heapq
import sys
input = sys.stdin.readline
def solution(n, d, c, dependency_list):
# BFS, 다익스트라랑 비슷함
# 트리 / tree[i] = [[i 의 자식 노드, 시간], ...]
tree = [[] for _ in range(n+1)]
# 트리 정리
for a, b, s in dependency_list:
# 트리 정리
tree[b].append([a, s])
# 큐
queue = [[0, c]]
# 시스템상 가장 큰 수
inf = float('INF')
# 현재 노드까지 감염되는데 걸리는 최단 시간
time_list = [inf for _ in range(n+1)]
# 감염된 노드 수
infected = set([c])
# 트리 순회
while queue:
# 현재 노드, 시간
now_time, now_node = heapq.heappop(queue)
# 현재 시간이 최단 시간보다 길면 탐험할 필요 없음
if time_list[now_node] < now_time:
continue
# 자식 탐색
for node, time in tree[now_node]:
# 다음 노드까지의 시간이 현재 최단시간보다 길면 탐색할 필요 없음
if time_list[node] > now_time + time:
# 최단 시간 최신화
time_list[node] = now_time + time
# 큐에 추가
heapq.heappush(queue, [now_time+time, node])
# 감염된 노드에 추가
infected.add(node)
print(f'{len(infected)} {max([i if i != inf else 0 for i in time_list])}')
T = int(input())
for _ in range(T):
n, d, c = map(int, input().split())
dependency_list = [list(map(int, input().strip().split())) for _ in range(d)]
solution(n, d, c, dependency_list)
728x90
'Coding Test > BaekJoon_Python' 카테고리의 다른 글
| 백준 17608 <막대기> Python (1) | 2024.01.24 |
|---|---|
| 백준 1967 <트리의 지름> Python (2) | 2024.01.23 |
| 백준 3977 <축구 전술> Python (1) | 2024.01.05 |
| 백준 4196 <도미노> Python (1) | 2024.01.03 |
| 백준 2150 <Strongly Connected Component> Python (1) | 2024.01.03 |