forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path9.java
More file actions
77 lines (65 loc) Β· 2.61 KB
/
9.java
File metadata and controls
77 lines (65 loc) Β· 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.util.*;
public class Main {
// λ
Έλμ κ°μ(V)
public static int v;
// λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
public static int[] indegree = new int[501];
// κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν μ°κ²° 리μ€νΈ μ΄κΈ°ν
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
// κ° κ°μ μκ°μ 0μΌλ‘ μ΄κΈ°ν
public static int[] times = new int[501];
// μμ μ λ ¬ ν¨μ
public static void topologySort() {
int[] result = new int[501]; // μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ λ°°μ΄
for (int i = 1; i <= v; i++) {
result[i] = times[i];
}
Queue<Integer> q = new LinkedList<>(); // ν λΌμ΄λΈλ¬λ¦¬ μ¬μ©
// μ²μ μμν λλ μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for (int i = 1; i <= v; i++) {
if (indegree[i] == 0) {
q.offer(i);
}
}
// νκ° λΉ λκΉμ§ λ°λ³΅
while (!q.isEmpty()) {
// νμμ μμ κΊΌλ΄κΈ°
int now = q.poll();
// ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for (int i = 0; i < graph.get(now).size(); i++) {
result[graph.get(now).get(i)] = Math.max(result[graph.get(now).get(i)], result[now] + times[graph.get(now).get(i)]);
indegree[graph.get(now).get(i)] -= 1;
// μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λλ λ
Έλλ₯Ό νμ μ½μ
if (indegree[graph.get(now).get(i)] == 0) {
q.offer(graph.get(now).get(i));
}
}
}
// μμ μ λ ¬μ μνν κ²°κ³Ό μΆλ ₯
for (int i = 1; i <= v; i++) {
System.out.println(result[i]);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
v = sc.nextInt();
// κ·Έλν μ΄κΈ°ν
for (int i = 0; i <= v; i++) {
graph.add(new ArrayList<Integer>());
}
// λ°©ν₯ κ·Έλνμ λͺ¨λ κ°μ μ 보λ₯Ό μ
λ ₯λ°κΈ°
for (int i = 1; i <= v; i++) {
// 첫 λ²μ§Έ μλ μκ° μ 보λ₯Ό λ΄κ³ μμ
int x = sc.nextInt();
times[i] = x;
// ν΄λΉ κ°μλ₯Ό λ£κΈ° μν΄ λ¨Όμ λ€μ΄μΌ νλ κ°μλ€μ λ²νΈ μ
λ ₯
while (true) {
x = sc.nextInt();
if (x == -1) break;
indegree[i] += 1;
graph.get(x).add(i);
}
}
topologySort();
}
}