Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class Main {
- static List<Integer>ans;
- static boolean[] used;
- static List<Function>functions;
- static List<Integer>order;
- public static void main (String[] args) throws IOException {
- Scanner scanner = new Scanner(new InputStreamReader(System.in));
- int n = scanner.nextInt();
- used = new boolean[n];
- functions = new ArrayList<>(n);
- ans = new ArrayList<>();
- order = new ArrayList<>();
- for (int i = 0; i < n; i++) {
- String line = scanner.nextLine();
- if (line.isEmpty()) {
- i--;
- continue;
- }
- order.add(i);
- Scanner sc = new Scanner(line);
- String name = sc.next();
- functions.add(new Function(name));
- //System.out.println(name);
- while (sc.hasNext()) {
- int prev = sc.nextInt();
- functions.get(i).dep.add(prev);
- }
- }
- Collections.sort(order, (x, y) -> functions.get(x).name.compareTo(functions.get(y).name));
- for (int i = 0; i < n; i++) {
- Collections.sort(functions.get(i).dep, (x, y) -> functions.get(x).name.compareTo(functions.get(y).name));
- /*System.out.print(functions.get(i).name + ": ");
- for (int j = 0; j < functions.get(i).dep.size(); j++) {
- System.out.print(functions.get(i).dep.get(j) + " ");
- }
- System.out.println();*/
- }
- for (int i = 0; i < n; i++) {
- if (!used[ order.get(i) ]) {
- dfs(order.get(i));
- }
- }
- //Collections.reverse(ans);
- for (Integer an : ans) {
- System.out.println(functions.get(an).name);
- }
- }
- static void dfs(int v) {
- used[v] = true;
- for (int to : functions.get(v).dep) {
- if (!used[to]) {
- dfs(to);
- }
- }
- ans.add(v);
- }
- static class Function {
- String name;
- ArrayList<Integer> dep;
- Function(String name) {
- this.name = name;
- dep = new ArrayList<>();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment