fork download
  1. /**
  2.  * Created by ruthless on 27/4/16.
  3.  */
  4.  
  5.  
  6. import java.io.*;
  7. import java.util.*;
  8.  
  9.  
  10. class spoj_cc {
  11. static LinkedList<Integer>[] list;
  12. static LinkedList<Integer>[] tlist;
  13. static boolean visited[];
  14. static Stack<Integer> ts;
  15. static int gno;
  16. static int comp[];
  17.  
  18. public static void DFS1(int x)
  19. {
  20. if(visited[x]) return;
  21. visited[x]=true;
  22.  
  23. for(int i=0;i<list[x].size();i++) DFS1(list[x].get(i));
  24. ts.push(x);
  25. }
  26.  
  27. public static void DFS2(int x)
  28. {
  29. if(visited[x]) return;
  30. visited[x]=true;
  31. for (int i=0;i<tlist[x].size();i++) DFS2(tlist[x].get(i));
  32. comp[x]=gno;
  33. }
  34. public static void main(String args[]) throws IOException {
  35. String[] s=br.readLine().trim().split(" ");
  36. int v=Integer.parseInt(s[0]);
  37. int e=Integer.parseInt(s[1]);
  38. list=new LinkedList[v+1];
  39. tlist=new LinkedList[v+1];
  40. visited=new boolean[v+1];
  41. ts=new Stack<>();
  42. gno=0;
  43. comp=new int[v+1];
  44. for (int i=1;i<=v;i++)
  45. {
  46. list[i]=new LinkedList();
  47. tlist[i]=new LinkedList<>();
  48. }
  49. while (e-->0)
  50. {
  51. s=br.readLine().trim().split(" ");
  52. int f=Integer.parseInt(s[0]);
  53. int t=Integer.parseInt(s[1]);
  54. list[f].add(t);
  55. tlist[t].add(f);
  56. }
  57.  
  58. for (int i=1;i<=v;i++)
  59. {
  60. DFS1(i);
  61. }
  62.  
  63. visited=new boolean[v+1];
  64. while(!ts.isEmpty())
  65. {
  66. int node=ts.pop();
  67. if(!visited[node])
  68. {
  69. gno+=1;
  70. DFS2(node);
  71. }
  72. }
  73. int outdeg[]=new int[gno+1];
  74. for(int i=1;i<=v;i++)
  75. {
  76. for (int j=0;j<list[i].size();j++)
  77. {
  78. if(comp[i]!=comp[list[i].get(j)])
  79. {
  80. outdeg[comp[i]]+=1;
  81. }
  82. }
  83. }
  84.  
  85. long count=0;
  86.  
  87. String sb ="";
  88. for (int i = 1; i <= v; i++) {
  89. if (outdeg[comp[i]] == 0) {
  90. count += 1;
  91. sb+=i+" ";
  92. }
  93. }
  94.  
  95. bw.write(count + "\n");
  96. bw.write(sb.trim() + "");
  97. bw.close();
  98. }
  99. }
  100.  
Success #stdin #stdout 0.11s 320576KB
stdin
4 4
1 2
2 1
3 2
4 3
stdout
2
1 2