[Algorithm] boj_10282 (Dijkstra)

bagt13·2025년 6월 18일
0

Algorithm

목록 보기
22/23

문제

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)가 두 번 이상 존재하지 않는다.

출력

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



접근 방법

  • 얼핏 보면 BFS로 간단하게 감염을 전파하여 풀 수 있을것 같지만, 문제에는 명시되지 않은 다음 경우가 존재한다.

    • a-b 감염 경로가 여러개일 수 있으므로, 최소 시간이 걸리는 루트를 구해야 한다.
  • 따라서 다익스트라 알고리즘을 통해 최소 시간을 갱신하며 풀어야한다.


코드

import java.io.*;
import java.util.*;
import java.io.*;
import java.util.*;

public class boj_10282_dijkstra {

    static int T, N, D, C;
    static List<List<Edge>> graph;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        T = Integer.parseInt(br.readLine());

        while (T-- > 0) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            N = Integer.parseInt(st.nextToken());
            D = Integer.parseInt(st.nextToken());
            C = Integer.parseInt(st.nextToken());

            //init graph
            graph = new ArrayList<>();
            for (int i = 0; i <= N; i++) {
                graph.add(new ArrayList<>());
            }

			//input dependencies
            for (int i = 0; i < D; i++) {
                st = new StringTokenizer(br.readLine());
                int a = Integer.parseInt(st.nextToken());
                int b = Integer.parseInt(st.nextToken());
                int s = Integer.parseInt(st.nextToken());

                graph.get(b).add(new Edge(a, s)); // b → a (감염 전파)
            }

            //해당 지점에서부터의 최단 감염 시간
            int[] dist = new int[N + 1];
            Arrays.fill(dist, Integer.MAX_VALUE);
            dist[C] = 0;

			//감염 시간 최신순(오름차순) 정렬
            PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(e -> e.cost));
            pq.offer(new Edge(C, 0));

            while (!pq.isEmpty()) {
                Edge now = pq.poll();
								
				//이미 더 빠르게 처리된 적 있다면 -> skip
                if (dist[now.to] < now.cost) continue; 

                for (Edge next : graph.get(now.to)) {
                	//다음 전파될 컴퓨터도 최소 시간인지 판별 후 갱신
                    if (dist[next.to] > dist[now.to] + next.cost) {
                        dist[next.to] = dist[now.to] + next.cost;
                        pq.offer(new Edge(next.to, dist[next.to]));
                    }
                }
            }

            int count = 0;
            int time = 0;
            for (int i = 1; i <= N; i++) {
                if (dist[i] != Integer.MAX_VALUE) {
                    count++;
                    time = Math.max(time, dist[i]);
                }
            }

            sb.append(count).append(" ").append(time);
        }

        System.out.print(sb);
    }

    private static class Edge {
        int to, cost;

        Edge(int to, int cost) {
            this.to = to;
            this.cost = cost;
        }
    }
}
profile
백엔드 개발자입니다😄

0개의 댓글