|
| 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 | + |
| 9 | + static int nodeCnt, preCnt,ans; |
| 10 | + static Node[] nodes;; |
| 11 | + static StringBuilder sb = new StringBuilder(); |
| 12 | + |
| 13 | + |
| 14 | + static class Node{ |
| 15 | + int semester; |
| 16 | + int num; |
| 17 | + int parentCnt; |
| 18 | + HashSet<Node> children; |
| 19 | + |
| 20 | + public Node(int num) { |
| 21 | + semester = 1; |
| 22 | + parentCnt = 0; |
| 23 | + this.num = num; |
| 24 | + children = new HashSet<>(); |
| 25 | + |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + public static void main(String[] args) throws NumberFormatException, IOException { |
| 30 | + init(); |
| 31 | + process(); |
| 32 | + print(); |
| 33 | + |
| 34 | + |
| 35 | + } |
| 36 | + |
| 37 | + public static void init() throws NumberFormatException, IOException { |
| 38 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 39 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 40 | + nodeCnt = Integer.parseInt(st.nextToken()); |
| 41 | + preCnt = Integer.parseInt(st.nextToken()); |
| 42 | + nodes = new Node[nodeCnt+1]; |
| 43 | + for (int i = 1; i <= nodeCnt; i++) { |
| 44 | + nodes[i] = new Node(i); |
| 45 | + } |
| 46 | + |
| 47 | + for (int i = 0; i < preCnt; i++) { |
| 48 | + st = new StringTokenizer(br.readLine()); |
| 49 | + int parent = Integer.parseInt(st.nextToken()); |
| 50 | + int child = Integer.parseInt(st.nextToken()); |
| 51 | + |
| 52 | + nodes[parent].children.add(nodes[child]); |
| 53 | + nodes[child].parentCnt++; |
| 54 | + |
| 55 | + } |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + public static void process() { |
| 60 | + Queue<Node> pq = new LinkedList<>(); |
| 61 | + |
| 62 | + for (int i = 1; i <= nodeCnt; i++ ) { |
| 63 | + |
| 64 | + Node node = nodes[i]; |
| 65 | + if (node.parentCnt ==0) pq.add(node); |
| 66 | + |
| 67 | + } |
| 68 | + |
| 69 | + while (!pq.isEmpty()) { |
| 70 | + Node node = pq.poll(); |
| 71 | + for (Node n: node.children ) { |
| 72 | + n.parentCnt--; |
| 73 | + if (n.parentCnt == 0) { |
| 74 | + n.semester = node.semester+1; |
| 75 | + pq.add(n); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + |
| 81 | + for (int i = 1; i<= nodeCnt; i++) { |
| 82 | + sb.append(nodes[i].semester+ " "); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + |
| 87 | + |
| 88 | + public static void print() { |
| 89 | + System.out.println(sb.toString()); |
| 90 | + } |
| 91 | +} |
| 92 | +``` |
0 commit comments