fork download
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Spoj
  5. {
  6. public static void main(String args[])throws Exception
  7. {
  8. StringBuilder sb=new StringBuilder();
  9. int t=Integer.parseInt(bu.readLine()),cs=1;
  10. while(t-->0)
  11. {
  12. sb.append("Scenario #"+cs+++":\n");
  13. StringTokenizer st=new StringTokenizer(bu.readLine());
  14. int n=Integer.parseInt(st.nextToken()),r=Integer.parseInt(st.nextToken()),i;
  15. ArrayList<Integer> g[]=new ArrayList[n];
  16. boolean vis[]=new boolean[n]; int deg[]=new int[n];
  17. for(i=0;i<n;i++)
  18. g[i]=new ArrayList<>();
  19. for(i=0;i<r;i++)
  20. {
  21. st=new StringTokenizer(bu.readLine());
  22. int l=Integer.parseInt(st.nextToken()),f=Integer.parseInt(st.nextToken());
  23. g[f].add(l);
  24. deg[l]++;
  25. }
  26.  
  27. Queue<Pair> q=new LinkedList<>();
  28. ArrayList<Pair> ans=new ArrayList<>();
  29. for(i=0;i<n;i++)
  30. if(deg[i]==0)
  31. {
  32. vis[i]=true;
  33. q.add(new Pair(i,1));
  34. }
  35.  
  36. while(!q.isEmpty())
  37. {
  38. Pair p=q.poll();
  39. ans.add(p);
  40. for(i=0;i<g[p.x].size();i++)
  41. if(!vis[g[p.x].get(i)])
  42. {
  43. deg[g[p.x].get(i)]--;
  44. if(deg[g[p.x].get(i)]==0)
  45. {
  46. vis[g[p.x].get(i)]=true;
  47. q.add(new Pair(g[p.x].get(i),p.y+1));
  48. }
  49. }
  50. }
  51.  
  52. Collections.sort(ans, new Comparator<Pair>() {
  53. public int compare(Pair o1, Pair o2) {
  54. if(o1.y>o2.y) return 1;
  55. else if(o1.y==o2.y) return o1.x>o2.x?1:-1;
  56. else return -1;
  57. }});
  58.  
  59. for(i=0;i<ans.size();i++)
  60. sb.append(ans.get(i).y+" "+ans.get(i).x+"\n");
  61. }
  62. System.out.print(sb);
  63. }
  64.  
  65. static class Pair
  66. {
  67. int x,y;
  68. Pair(int a,int b)
  69. {
  70. x=a; y=b;
  71. }
  72. }
  73. }
  74.  
Success #stdin #stdout 0.11s 36472KB
stdin
2
5 6
2 0
2 4
1 4
1 2
3 2
4 0
5 4
1 0
2 0
3 2
4 2
stdout
Scenario #1:
1 0
2 4
3 2
4 1
4 3
Scenario #2:
1 0
2 1
2 2
3 3
3 4