-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBOJ2252.java
More file actions
81 lines (66 loc) · 2.07 KB
/
BOJ2252.java
File metadata and controls
81 lines (66 loc) · 2.07 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
78
79
80
81
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOJ2252 {
/**
* Topological Sorting
* 특정 작업을 위해서 선행되어야 하는 작업이 있을 때
* ex) install package
*/
static int n, m;
static List<Integer>[] graph;
static List<Integer> answer;
static int[] inDegree;
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
// set n, m
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
inDegree = new int[n + 1];
// set tree
graph = new List[n + 1];
for (int i = 1; i <= n; i++)
graph[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int parent = Integer.parseInt(st.nextToken());
int child = Integer.parseInt(st.nextToken());
graph[parent].add(child);
inDegree[child]++;
}
answer = new ArrayList<>();
}
public static void main(String[] args) throws IOException {
input();
process();
}
private static void process() {
// 위상 정렬
topologicalSorting();
// print answer
for (int i : answer)
System.out.print(i + " ");
}
private static void topologicalSorting() {
Queue<Integer> queue = new LinkedList<>();
// add start vertex
for (int i = 1; i <= n; i++) {
if (inDegree[i] == 0) {
queue.add(i);
}
}
while (!queue.isEmpty()) {
int thisVertex = queue.poll();
answer.add(thisVertex);
for (int i : graph[thisVertex]) {
inDegree[i]--;
if (inDegree[i] == 0) {
queue.add(i);
}
}
}
}
}