|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 8 | + static int n, d, c; |
| 9 | + static List<Info>[] graph; // 인접 리스트 |
| 10 | + |
| 11 | + static class Info implements Comparable<Info> { |
| 12 | + int id; |
| 13 | + int sec; |
| 14 | + public Info(int id, int sec) { |
| 15 | + this.id = id; |
| 16 | + this.sec = sec; |
| 17 | + } |
| 18 | + @Override |
| 19 | + public int compareTo(Info o) { |
| 20 | + return Integer.compare(this.sec, o.sec); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + public static void main(String[] args) throws IOException { |
| 25 | + int T = Integer.parseInt(br.readLine()); |
| 26 | + for (int tc = 1; tc <= T; tc++) { |
| 27 | + input(); |
| 28 | + // 총 감염되는 컴퓨터 수, 마지막 컴퓨터가 감염되기까지 걸리는 시간 |
| 29 | + dijkstra(c); |
| 30 | + } |
| 31 | + br.close(); |
| 32 | + } |
| 33 | + |
| 34 | + private static void dijkstra(int start) { |
| 35 | + PriorityQueue<Info> pq = new PriorityQueue<>(); |
| 36 | + |
| 37 | + int[] dist = new int[n+1]; |
| 38 | + for (int i = 0; i < n+1; i++) { |
| 39 | + dist[i] = -1; |
| 40 | + } |
| 41 | + dist[start] = 0; |
| 42 | + pq.add(new Info(start, 0)); |
| 43 | + |
| 44 | + while (!pq.isEmpty()) { |
| 45 | + Info info = pq.poll(); |
| 46 | + int current = info.id; |
| 47 | + if (dist[current] < info.sec) continue; // 이미 더 빠르게 방문한 적이 있으면 skip |
| 48 | + for (Info next : graph[current]) { |
| 49 | + if (dist[next.id] == -1 || dist[next.id] > dist[current] + next.sec ) { |
| 50 | + dist[next.id] = dist[current] + next.sec; |
| 51 | + pq.add(next); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + int cnt = 0; |
| 57 | + int time = -1; |
| 58 | + for (int i = 1; i <= n; i++) { |
| 59 | + if (dist[i] == -1) { continue; } |
| 60 | + cnt++; |
| 61 | + time = Integer.max(time, dist[i]); |
| 62 | + } |
| 63 | + // 총 감염되는 컴퓨터 수 |
| 64 | + // 감염되기까지 걸리는 시간 |
| 65 | + System.out.println(cnt + " " + time); |
| 66 | + } |
| 67 | + |
| 68 | + private static void input() throws IOException { |
| 69 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 70 | + n = Integer.parseInt(st.nextToken()); |
| 71 | + d = Integer.parseInt(st.nextToken()); |
| 72 | + c = Integer.parseInt(st.nextToken()); |
| 73 | + graph = new List[n+1]; |
| 74 | + for (int i = 1; i < n+1; i++) { |
| 75 | + graph[i] = new ArrayList<>(); |
| 76 | + } |
| 77 | + for (int i = 0; i < d; i++) { |
| 78 | + st = new StringTokenizer(br.readLine()); |
| 79 | + // 컴퓨터 a가 컴퓨터 b를 의존하며, 컴퓨터 b가 감염되면 s초 후 컴퓨터 a도 감염된다. |
| 80 | + int a = Integer.parseInt(st.nextToken()); |
| 81 | + int b = Integer.parseInt(st.nextToken()); |
| 82 | + int s = Integer.parseInt(st.nextToken()); |
| 83 | + graph[b].add(new Info(a, s)); |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +``` |
0 commit comments