fork(2) download
  1.  
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.Stack;
  9.  
  10. public class Main {
  11.  
  12.  
  13. static ArrayList<Integer> [] arr;
  14. static int visited [];
  15. static Stack<Integer> a = new Stack<Integer>();
  16. static boolean flag=false;
  17.  
  18. public static void graphcheck(int node){ //method to check if there is a cycle in the graph
  19. visited[node] = 2;
  20. for(int i=0;i<arr[node].size();i++){
  21. int u =arr[node].get(i);
  22. if(visited[u]==0){
  23. graphcheck(u);
  24. }else if(visited[u]==2){
  25. flag=true;
  26. return;
  27. }
  28. }
  29. visited[node] = 1;
  30. }
  31.  
  32. public static void dfs2(int node){ //method to get one possible topological sort which I want to extend to get all posibilites
  33. visited[node] = 1;
  34. for(int i=0;i<arr[node].size();i++){
  35. int u =arr[node].get(i);
  36. if(visited[u]==0){
  37. dfs2(u);
  38. }
  39. }
  40. a.push(node);
  41. }
  42.  
  43. public static void main(String[] args) throws NumberFormatException, IOException {
  44. int tc = Integer.parseInt(br.readLine());
  45. for(int k=0;k<tc;k++){
  46. br.readLine();
  47.  
  48. String h[]= br.readLine().split(" ");
  49. int n= h.length;
  50. arr=new ArrayList[n];
  51. visited = new int[n];
  52. for( int i = 0; i < n; i++) {
  53. arr[ i] = new ArrayList<Integer>();
  54. }
  55. String q[]=br.readLine().split(" ");
  56. int y=q.length;
  57. for(int i=0;i<y;i++){
  58. int x=0;
  59. int z=0;
  60. for(int j=0;j<n;j++){
  61. if(q[i].charAt(0)==h[j].charAt(0)){
  62. x=j;
  63. }else if(q[i].charAt(2)==h[j].charAt(0)){
  64. z=j;
  65. }
  66. }
  67. if(q[i].charAt(1)=='<'){
  68. // System.out.println(q[i].charAt(0)-'A'+" "+(q[i].charAt(2)-'A'));
  69. arr[x].add(z);
  70. }
  71. }
  72. for(int i=0;i<n;i++){
  73. if(visited[i]==0)
  74. graphcheck(i);
  75. }
  76. if(flag){
  77. System.out.println("NO");
  78. }else{
  79. a.clear();
  80. Arrays.fill(visited, 0);
  81. for(int i=0;i<n;i++){
  82. if(visited[i]==0){
  83. dfs2(i);
  84. }
  85. }
  86. int z= a.size();
  87. for(int i=0;i<z;i++){
  88. int x =a.pop();
  89. System.out.print(h[x]+" ");
  90. }
  91. System.out.println();
  92. }
  93.  
  94.  
  95. }
  96. }
  97. }
  98.  
Success #stdin #stdout 0.07s 380160KB
stdin
2

A B F G
A<B B<F

A B C
A<B B<A
stdout
G A B F 
NO