3 분 소요

1. 문제

https://www.acmicpc.net/problem/10282

  • 다익스트라 문제
// 문제
최흉최악의 해커 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


2. 핵심 아이디어

  • 도달할 수 있는 정점들의 개수와 최대 거리를 출력
  • 정점의 개수 N이 최대 10,000이고, 간선의 개수 D는 최대 100,000
  • 우선순위 큐를 이용하여, 시간 복잡도는 O(NlogD)로 해결할 수 있음


3. Python 문제풀이

import sys
import heapq
input = sys.stdin.readline

def dijkstra(start) :
  heap_data = []
  heapq.heappush(heap_data, (0, start))
  distance[start] = 0
  while heap_data :
    dist, now = heapq.heappop(heap_data)
    if distance[now] < dist :
      continue
    for i in adj[now] :
      cost = dist + i[1]
      if distance[i[0]] > cost :
        distance[i[0]] = cost
        heapq.heappush(heap_data, (cost, i[0]))

for _ in range(int(input())) :
  n, m, start = map(int, input().split())
  adj = [[] for _ in range(n + 1)]
  distance = [1e9] * (n + 1)
  for _ in range(m) :
    x, y, cost = map(int, input().split())
    adj[y].append((x, cost))
  dijkstra(start)
  count = 0
  max_distance = 0
  for i in distance :
    if i != 1e9 :
      count += 1
      if i > max_distance :
        max_distance = i
  print(count, max_distance)


4. Java 문제풀이

import java.util.*;

public class Main {
  static int n, d, c;
  static ArrayList<Node>[] list;
  static int count;
  static boolean[] visited;
  static int[] dist;

  public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);

      int t = sc.nextInt();
      for(int i = 0; i < t; i++) {
        n = sc.nextInt();
        d = sc.nextInt();
        c = sc.nextInt();

        list = new ArrayList[n + 1];
        for(int j = 1; j <= n; j++) {
          list[j] = new ArrayList<>();
        }

        for(int j = 0; j < d; j++) {
          int a = sc.nextInt();
          int b = sc.nextInt();
          int s = sc.nextInt();
          list[b].add(new Node(a, s));
        }

        count = 0;
        dist = new int[n + 1];
        visited = new boolean[n + 1];

        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[c] = 0;

        dijkstra();
        int max_distance = 0;
        for(int j = 1; j <= n; j++) {
          if(dist[j] != Integer.MAX_VALUE) max_distance = Math.max(max_distance, dist[j]);
        }

        System.out.println(count + " " + max_distance);
      }
  }

  public static void dijkstra() {
    PriorityQueue<Node> q = new PriorityQueue<>();
    q.offer(new Node(c, 0));

    while(!q.isEmpty()) {
      Node current = q.poll();

      if(visited[current.n] == false) {
        visited[current.n] = true;
        count++;
      }
      else continue;

      for(int i = 0; i < list[current.n].size(); i++) {
        Node next = list[current.n].get(i);
        if(dist[next.n] > dist[current.n] + next.s) {
          dist[next.n] = dist[current.n] + next.s;
          q.offer(new Node(next.n, dist[next.n]));
        }
      }
    }
  }

  public static class Node implements Comparable<Node> {
    int n;
    int s;

    public Node(int n, int s) {
      this.n = n;
      this.s = s;
    }

    @Override
    public int compareTo(Node n) {
      return this.s - n.s;
    }
  }
}

댓글남기기