|
| 1 | +package Graph.P21276; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +public class Main { |
| 9 | + |
| 10 | + static int N, M; |
| 11 | + static String[] names; |
| 12 | + static HashMap<String, Integer> idx = new HashMap<>(); |
| 13 | + |
| 14 | + static LinkedList<Integer>[] children, graph; |
| 15 | + static int[] indegree; |
| 16 | + |
| 17 | + public static void main(String[] args) throws Exception { |
| 18 | + System.setIn(new FileInputStream("src/Graph/P21276/input.txt")); |
| 19 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 20 | + |
| 21 | + N = Integer.parseInt(br.readLine()); |
| 22 | + names = new String[N]; |
| 23 | + children = new LinkedList[N]; |
| 24 | + graph = new LinkedList[N]; |
| 25 | + indegree = new int[N]; |
| 26 | + |
| 27 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 28 | + for (int i = 0; i < N; i++) names[i] = st.nextToken(); |
| 29 | + |
| 30 | + Arrays.sort(names); |
| 31 | + for (int i = 0; i < N; i++) { |
| 32 | + idx.put(names[i], i); |
| 33 | + children[i] = new LinkedList<>(); |
| 34 | + graph[i] = new LinkedList<>(); |
| 35 | + } |
| 36 | + |
| 37 | + M = Integer.parseInt(br.readLine()); |
| 38 | + while (M-- > 0) { |
| 39 | + st = new StringTokenizer(br.readLine()); |
| 40 | + int X = idx.get(st.nextToken()), Y = idx.get(st.nextToken()); |
| 41 | + graph[Y].add(X); |
| 42 | + indegree[X] ++; |
| 43 | + } |
| 44 | + |
| 45 | + Queue<Integer> q = new LinkedList<>(); |
| 46 | + LinkedList<Integer> root = new LinkedList<>(); |
| 47 | + for (int i = 0; i < N; i++) { |
| 48 | + if (indegree[i] == 0) { |
| 49 | + q.offer(i); |
| 50 | + root.add(i); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + while (!q.isEmpty()) { |
| 55 | + int cur = q.poll(); |
| 56 | + for (int next : graph[cur]) { |
| 57 | + indegree[next] --; |
| 58 | + if (indegree[next] == 0) { |
| 59 | + children[cur].add(next); |
| 60 | + q.offer(next); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + System.out.println(root.size()); |
| 66 | + for (Integer s : root) System.out.print(names[s] + " "); |
| 67 | + System.out.println(); |
| 68 | + |
| 69 | + for (int i = 0; i < N; i++) { |
| 70 | + System.out.print(names[i] + " " + children[i].size() + " "); |
| 71 | + Collections.sort(children[i]); |
| 72 | + for (Integer c : children[i]) System.out.print(names[c] + " "); |
| 73 | + System.out.println(); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments