abdukodir

Untitled

Nov 13th, 2015
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. public class Main {
  6. static List<Integer>ans;
  7. static boolean[] used;
  8. static List<Function>functions;
  9. static List<Integer>order;
  10. public static void main (String[] args) throws IOException {
  11. Scanner scanner = new Scanner(new InputStreamReader(System.in));
  12. int n = scanner.nextInt();
  13. used = new boolean[n];
  14. functions = new ArrayList<>(n);
  15. ans = new ArrayList<>();
  16. order = new ArrayList<>();
  17. for (int i = 0; i < n; i++) {
  18. String line = scanner.nextLine();
  19. if (line.isEmpty()) {
  20. i--;
  21. continue;
  22. }
  23. order.add(i);
  24. Scanner sc = new Scanner(line);
  25. String name = sc.next();
  26. functions.add(new Function(name));
  27. //System.out.println(name);
  28. while (sc.hasNext()) {
  29. int prev = sc.nextInt();
  30. functions.get(i).dep.add(prev);
  31. }
  32. }
  33. Collections.sort(order, (x, y) -> functions.get(x).name.compareTo(functions.get(y).name));
  34. for (int i = 0; i < n; i++) {
  35. Collections.sort(functions.get(i).dep, (x, y) -> functions.get(x).name.compareTo(functions.get(y).name));
  36. /*System.out.print(functions.get(i).name + ": ");
  37. for (int j = 0; j < functions.get(i).dep.size(); j++) {
  38. System.out.print(functions.get(i).dep.get(j) + " ");
  39. }
  40. System.out.println();*/
  41. }
  42. for (int i = 0; i < n; i++) {
  43. if (!used[ order.get(i) ]) {
  44. dfs(order.get(i));
  45. }
  46. }
  47. //Collections.reverse(ans);
  48. for (Integer an : ans) {
  49. System.out.println(functions.get(an).name);
  50. }
  51. }
  52. static void dfs(int v) {
  53. used[v] = true;
  54. for (int to : functions.get(v).dep) {
  55. if (!used[to]) {
  56. dfs(to);
  57. }
  58. }
  59. ans.add(v);
  60. }
  61. static class Function {
  62. String name;
  63. ArrayList<Integer> dep;
  64. Function(String name) {
  65. this.name = name;
  66. dep = new ArrayList<>();
  67. }
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment