차밍이

[Python] 백준 10282번 해킹 - 다익스트라(Dijkstra) 알고리즘 예제 문제 본문

파이썬/알고리즘

[Python] 백준 10282번 해킹 - 다익스트라(Dijkstra) 알고리즘 예제 문제

2022. 4. 13. 13:34
반응형

해킹

시간 제한 메모리 제한 제출 정답 맞힌 사람 정답 비율
2 초 256 MB 8889 3518 2481 38.453%

문제

최흉최악의 해커 yum3이 네트워크 시설의 한 컴퓨터를 해킹했다! 이제 서로에 의존하는 컴퓨터들은 점차 하나둘 전염되기 시작한다. 어떤 컴퓨터 a가 다른 컴퓨터 b에 의존한다면, b가 감염되면 그로부터 일정 시간 뒤 a도 감염되고 만다. 이때 b가 a를 의존하지 않는다면, a가 감염되더라도 b는 안전하다.

최흉최악의 해커 yum3이 해킹한 컴퓨터 번호와 각 의존성이 주어질 때, 해킹당한 컴퓨터까지 포함하여 총 몇 대의 컴퓨터가 감염되며 그에 걸리는 시간이 얼마인지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 테스트 케이스의 개수가 주어진다. 테스트 케이스의 개수는 최대 100개이다. 각 테스트 케이스는 다음과 같이 이루어져 있다.

  • 첫째 줄에 컴퓨터 개수 n, 의존성 개수 d, 해킹당한 컴퓨터의 번호 c가 주어진다(1 ≤ n ≤ 10,000, 1 ≤ d ≤ 100,000, 1 ≤ c ≤ n).
  • 이어서 d개의 줄에 각 의존성을 나타내는 정수 a, b, s가 주어진다(1 ≤ a, b ≤ n, a ≠ b, 0 ≤ s ≤ 1,000). 이는 컴퓨터 a가 컴퓨터 b를 의존하며, 컴퓨터 b가 감염되면 s초 후 컴퓨터 a도 감염됨을 뜻한다.

각 테스트 케이스에서 같은 의존성 (a, b)가 두 번 이상 존재하지 않는다.

출력

각 테스트 케이스마다 한 줄에 걸쳐 총 감염되는 컴퓨터 수, 마지막 컴퓨터가 감염되기까지 걸리는 시간을 공백으로 구분지어 출력한다.

예제 입력 1

2
3 2 2
2 1 5
3 2 5
3 3 1
2 1 2
3 1 8
3 2 4

예제 출력 1

2 5
3 6

소스 코드 1

다익스트라 기본 예시 그대로 사용해서 graph를 작성하고

우선순위 큐와 다익스트라 큐를 위한 inf로 거리를 넣고 update해가는 과정을 dictionary로 구현함

import sys
import heapq

r = sys.stdin.readline

def dijkstra(graph, start):
    distances = {node : float('inf') for node in graph}
    distances[start] = 0
    queue = []
    heapq.heappush(queue, [distances[start], start])

    while queue:
        current_distance, current_node = heapq.heappop(queue)

        if distances[current_node] < current_distance:
            continue

        for adjacent, weight in graph[current_node].items():
            distance = current_distance + weight

            if distance < distances[adjacent]:
                distances[adjacent] = distance
                heapq.heappush(queue, [distance, adjacent])

    return distances

for _ in range(int(r())):
    n, d, c = map(int, r().split())
    queue = []
    graph = {}
    for _ in range(d):
        a, b, s = map(int, r().split())
        if b not in graph.keys():
            graph[b] = {a : s}
        else:
            graph[b][a] = s

    for j in [v for v in range(1, n+1) if v not in graph.keys()]:
        graph[j] = {}

    prior_queue = dijkstra(graph, c)
    computers = [v for v in prior_queue.values() if v != float('inf')]
    print(len(computers), max(computers))

소스 코드 2

전체적인 맥락에는 변화가 없다.

key 값이 그냥 일반 양의 정수 값들이므로 (computer n 값)

list 형태로 구현해도 구현해도 무방하다.

import sys
import heapq

r = sys.stdin.readline

def dijkstra(graph, start):
    distances = [float('inf')] * (n+1)
    distances[start] = 0
    queue = []
    heapq.heappush(queue, (distances[start], start))

    while queue:
        current_distance, current_node = heapq.heappop(queue)

        if distances[current_node] < current_distance:
            continue

        for adjacent, weight in graph[current_node].items():
            distance = current_distance + weight

            if distance < distances[adjacent]:
                distances[adjacent] = distance
                heapq.heappush(queue, (distance, adjacent))

    return distances

for _ in range(int(r())):
    n, d, c = map(int, r().split())
    queue = []
    graph = { i : dict() for i in range(n+1)}
    for _ in range(d):
        a, b, s = map(int, r().split())
        graph[b][a] = s

    prior_queue = dijkstra(graph, c)
    computers = [v for v in prior_queue if v != float('inf')]
    print(len(computers), max(computers))

문제 풀이

다익스트라 알고리즘의 가장 대표적인 문제이다.

해당 알고리즘을 공부하고 기본 예제를 보면 풀리는 문제이다.

출처

img

ICPC > Regionals > Europe > Northwestern European Regional Contest > Benelux Algorithm Programming Contest > BAPC 2014 Preliminaries B번

  • 문제를 번역한 사람: kks227

알고리즘 분류

반응형

관련된 글 보기

Comments