728x90
반응형
https://www.acmicpc.net/problem/1766
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
82
83
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
static class Node {
int v;
int z;
public Node(int v, int z) {
this.v = v;
this.z = z;
}
}
static int N;
static int M;
static int[] seq;
static ArrayList<ArrayList<Node>> grapgh;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
seq = new int[N + 1];
grapgh = new ArrayList<>();
for (int i = 0; i < N + 1; i++) {
grapgh.add(new ArrayList<>());
}
while (M-- > 0) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
seq[v]++;
grapgh.get(u).add(new Node(v, 0));
}
topologicalSort();
System.out.println(sb.toString());
}
static void topologicalSort() {
PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
if (o1.z == o2.z)
return o1.v - o2.v;
return o1.z - o2.z;
}
});
for (int i = 1; i < seq.length; i++) {
if (seq[i] == 0) {
pq.offer(new Node(i, 0));
}
}
while (!pq.isEmpty()) {
Node cur = pq.poll();
if (seq[cur.v] == 0) {
sb.append(cur.v).append(" ");
}
for (Node next : grapgh.get(cur.v)) {
seq[next.v]--;
if (seq[next.v] == 0) {
pq.offer(new Node(next.v, -1));
}
}
}
}
}
|
cs |
728x90
'Algorithm > BOJ' 카테고리의 다른 글
백준) 1074_Z (0) | 2023.05.16 |
---|---|
백준) 11003_최솟값 찾기 (2) | 2023.05.14 |
백준) 21276_계보 복원가 호석 (2) | 2023.05.13 |
백준) 1005_ACM Craft (1) | 2023.05.13 |
백준) 14676_영우는 사기꾼? (2) | 2023.05.13 |