|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +public class Main { |
| 8 | + static int nodeCnt, infoCnt; |
| 9 | + static Node[] nodes; |
| 10 | + static StringBuilder sb = new StringBuilder(); |
| 11 | + static class Node implements Comparable<Node>{ |
| 12 | + int num; |
| 13 | + int beforeCnt = 0; // 이 노드 전에 나와야 하는 노드 수 |
| 14 | + HashSet<Node> after = new HashSet<>(); |
| 15 | + |
| 16 | + |
| 17 | + |
| 18 | + public Node(int num) { |
| 19 | + this.num = num; |
| 20 | + } |
| 21 | + |
| 22 | + @Override |
| 23 | + public int compareTo(Node n) { |
| 24 | + return Integer.compare(this.num, n.num); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + |
| 29 | + public static void main(String[] args) throws NumberFormatException, IOException { |
| 30 | + init(); |
| 31 | + process(); |
| 32 | + print(); |
| 33 | + } |
| 34 | + |
| 35 | + public static void init() throws NumberFormatException, IOException { |
| 36 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 37 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 38 | + nodeCnt =Integer.parseInt(st.nextToken()); |
| 39 | + infoCnt = Integer.parseInt(st.nextToken()); |
| 40 | + nodes = new Node[nodeCnt+1]; |
| 41 | + |
| 42 | + for (int i = 1 ; i <= nodeCnt; i++) nodes[i] = new Node(i); |
| 43 | + for (int i = 0; i < infoCnt; i++) { |
| 44 | + st = new StringTokenizer(br.readLine()); |
| 45 | + int before = Integer.parseInt(st.nextToken()); |
| 46 | + int after = Integer.parseInt(st.nextToken()); |
| 47 | + |
| 48 | + nodes[after].beforeCnt++; |
| 49 | + nodes[before].after.add(nodes[after]); |
| 50 | + } |
| 51 | + |
| 52 | + } |
| 53 | + |
| 54 | + public static void process() { |
| 55 | + PriorityQueue<Node> pq = new PriorityQueue<>(); |
| 56 | + for (int i = 1; i<= nodeCnt; i++) { |
| 57 | + if (nodes[i].beforeCnt != 0 )continue; |
| 58 | + pq.add(nodes[i]); |
| 59 | + } |
| 60 | + |
| 61 | + while(!pq.isEmpty()) { |
| 62 | + Node n =pq.poll(); |
| 63 | + if ( n.beforeCnt != 0) { |
| 64 | + pq.add(n); |
| 65 | + continue; |
| 66 | + } |
| 67 | + |
| 68 | + sb.append(n.num).append(" "); |
| 69 | + |
| 70 | + for (Node b: n.after) { |
| 71 | + b.beforeCnt--; |
| 72 | + if (b.beforeCnt == 0) pq.add(b); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + } |
| 77 | + |
| 78 | + |
| 79 | + public static void print() { |
| 80 | + System.out.println(sb.toString()); |
| 81 | + } |
| 82 | +} |
| 83 | +``` |
0 commit comments