|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class BJ_1766_문제집 { |
| 6 | + |
| 7 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 8 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 9 | + private static final StringBuilder sb = new StringBuilder(); |
| 10 | + private static StringTokenizer st; |
| 11 | + |
| 12 | + private static int N, M; |
| 13 | + private static int[] inDegree; |
| 14 | + |
| 15 | + private static Queue<Integer> q; |
| 16 | + private static List<Integer>[] graph; |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + init(); |
| 20 | + sol(); |
| 21 | + } |
| 22 | + |
| 23 | + private static void init() throws IOException { |
| 24 | + st = new StringTokenizer(br.readLine()); |
| 25 | + N = Integer.parseInt(st.nextToken()); |
| 26 | + M = Integer.parseInt(st.nextToken()); |
| 27 | + |
| 28 | + graph = new ArrayList[N + 1]; |
| 29 | + for (int i = 1; i <= N; i++) { |
| 30 | + graph[i] = new ArrayList<>(); |
| 31 | + } |
| 32 | + |
| 33 | + inDegree = new int[N + 1]; |
| 34 | + for (int i = 0; i < M; i++) { |
| 35 | + st = new StringTokenizer(br.readLine()); |
| 36 | + |
| 37 | + int u = Integer.parseInt(st.nextToken()); |
| 38 | + int v = Integer.parseInt(st.nextToken()); |
| 39 | + |
| 40 | + graph[u].add(v); |
| 41 | + inDegree[v]++; |
| 42 | + } |
| 43 | + |
| 44 | + q = new PriorityQueue<>(); |
| 45 | + } |
| 46 | + |
| 47 | + private static void sol() throws IOException { |
| 48 | + for (int i = 1; i <= N; i++) { |
| 49 | + if (inDegree[i] == 0) { |
| 50 | + q.offer(i); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + while (!q.isEmpty()) { |
| 55 | + int cur = q.poll(); |
| 56 | + |
| 57 | + sb.append(cur).append(" "); |
| 58 | + |
| 59 | + for (int v : graph[cur]) { |
| 60 | + inDegree[v]--; |
| 61 | + if (inDegree[v] == 0) { |
| 62 | + q.offer(v); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + bw.write(sb.toString()); |
| 68 | + bw.flush(); |
| 69 | + bw.close(); |
| 70 | + br.close(); |
| 71 | + } |
| 72 | + |
| 73 | +} |
| 74 | +``` |
0 commit comments