forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path6.java
68 lines (57 loc) Β· 2.29 KB
/
6.java
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
import java.util.*;
public class Main {
// λ
Έλμ κ°μ(V)μ κ°μ μ κ°μ(E)
// λ
Έλμ κ°μλ μ΅λ 100,000κ°λΌκ³ κ°μ
public static int v, e;
// λͺ¨λ λ
Έλμ λν μ§μ
μ°¨μλ 0μΌλ‘ μ΄κΈ°ν
public static int[] indegree = new int[100001];
// κ° λ
Έλμ μ°κ²°λ κ°μ μ 보λ₯Ό λ΄κΈ° μν μ°κ²° 리μ€νΈ μ΄κΈ°ν
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>();
// μμ μ λ ¬ ν¨μ
public static void topologySort() {
ArrayList<Integer> result = new ArrayList<>(); // μκ³ λ¦¬μ¦ μν κ²°κ³Όλ₯Ό λ΄μ 리μ€νΈ
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();
result.add(now);
// ν΄λΉ μμμ μ°κ²°λ λ
Έλλ€μ μ§μ
μ°¨μμμ 1 λΉΌκΈ°
for (int i = 0; i < graph.get(now).size(); 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 = 0; i < result.size(); i++) {
System.out.print(result.get(i) + " ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
v = sc.nextInt();
e = sc.nextInt();
// κ·Έλν μ΄κΈ°ν
for (int i = 0; i <= v; i++) {
graph.add(new ArrayList<Integer>());
}
// λ°©ν₯ κ·Έλνμ λͺ¨λ κ°μ μ 보λ₯Ό μ
λ ₯ λ°κΈ°
for (int i = 0; i < e; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
graph.get(a).add(b); // μ μ Aμμ Bλ‘ μ΄λ κ°λ₯
// μ§μ
μ°¨μλ₯Ό 1 μ¦κ°
indegree[b] += 1;
}
topologySort();
}
}