|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int N; |
| 7 | + static int[] indegree; // 차수 저장 |
| 8 | + static int[] time; // 시간 저장 |
| 9 | + static List<Integer>[] adjList; // 인접 리스트 |
| 10 | + public static void main(String[] args) throws IOException { |
| 11 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 12 | + N = Integer.parseInt(br.readLine()); |
| 13 | + indegree = new int[N+1]; |
| 14 | + time = new int[N+1]; |
| 15 | + adjList = new List[N+1]; |
| 16 | + for (int i = 1; i <= N; i++) { |
| 17 | + adjList[i] = new ArrayList<>(); |
| 18 | + } |
| 19 | + |
| 20 | + for (int i = 1; i <= N; i++) { |
| 21 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 22 | + time[i] = Integer.parseInt(st.nextToken()); |
| 23 | + |
| 24 | + int cnt = Integer.parseInt(st.nextToken()); |
| 25 | + for (int j = 0; j < cnt; j++) { |
| 26 | + int prevId = Integer.parseInt(st.nextToken()); |
| 27 | + adjList[prevId].add(i); |
| 28 | + ++indegree[i]; |
| 29 | + } |
| 30 | + } |
| 31 | + int ans = topologicalSort(); |
| 32 | + System.out.println(ans); |
| 33 | + br.close(); |
| 34 | + } |
| 35 | + |
| 36 | + private static int topologicalSort() { |
| 37 | + |
| 38 | + Queue<Integer> q = new ArrayDeque<>(); |
| 39 | + int[] visitTime = new int[N+1]; |
| 40 | + |
| 41 | + for (int i = 1; i <= N; i++) { |
| 42 | + visitTime[i] = time[i]; |
| 43 | + if (indegree[i] == 0) q.offer(i); |
| 44 | + } |
| 45 | + |
| 46 | + while (!q.isEmpty()) { |
| 47 | + int current = q.poll(); |
| 48 | + for (int next : adjList[current]) { |
| 49 | + visitTime[next] = Math.max(visitTime[next], visitTime[current] + time[next]); |
| 50 | + if (--indegree[next] == 0) { |
| 51 | + q.offer(next); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + int ret = 0; |
| 57 | + for (int i = 1; i <= N; i++) { |
| 58 | + ret = Math.max(ret, visitTime[i]); |
| 59 | + } |
| 60 | + return ret; |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +``` |
0 commit comments