Guest User

Untitled

a guest
Jul 15th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. private class Node{
  2. HashSet<Integer> fromThis; //this -> neighbours
  3. HashSet<Integer> toThis; //neighbours -> this
  4. LinkedList<Integer> neighbours; //all vertexes from this
  5. Node(){
  6. fromThis=new HashSet<Integer>();
  7. toThis=new HashSet<Integer>();
  8. neighbours=new LinkedList<Integer>();
  9. }
  10. }
  11.  
  12. private class Graph{
  13. private BufferedReader in;
  14. private PrintWriter out;
  15. private StringTokenizer st;
  16. private Stack<Integer> stack;
  17. private int colors[];
  18. private int timeOfDeath[];
  19. private HashSet<Integer> doesntUsed;
  20.  
  21. private int vNum; //number of vertexes
  22. private int eNum; //number of edges
  23. private Node gr[];
  24.  
  25.  
  26. Graph(){
  27. vNum=0;
  28. eNum=0;
  29. }
  30. Graph(String arg)throws IOException{
  31. loadGraph(arg);
  32. }
  33.  
  34. public boolean isEmpty(){
  35. return vNum==0;
  36. }
  37. private void addEdge(int a, int b){ //from a to b
  38. gr[a-1].fromThis.add(b);
  39. gr[b-1].fromThis.add(a);
  40. gr[a-1].neighbours.add(b);
  41. eNum++;
  42. }
  43.  
  44. public void loadGraph(String arg)throws IOException{
  45. in=new BufferedReader(new FileReader(arg));
  46. String temp=in.readLine();
  47. st=new StringTokenizer(temp);
  48. vNum=Integer.parseInt(st.nextToken());
  49. int e=Integer.parseInt(st.nextToken());
  50. gr=new Node[vNum];
  51. int i;
  52. for (i=0; i<vNum; i++){
  53. gr[i] = new Node();
  54. }
  55. if (e>0){
  56. int a,b;
  57. for (i=0; i<e; i++){
  58. temp=in.readLine();
  59. st=new StringTokenizer(temp);
  60. a=Integer.parseInt(st.nextToken());
  61. b=Integer.parseInt(st.nextToken());
  62. addEdge(a, b);
  63. }
  64. }
  65. in.close();
  66. }
  67. public boolean topSort(int a){ //a- вершина с которой начинается...
  68. stack=new Stack<Integer>();
  69. colors=new int[vNum];
  70. doesntUsed=new HashSet<Integer>();
  71. timeOfDeath=new int[vNum];
  72. int i, index=a, temp;
  73. for (i=0; i<vNum; i++){
  74. colors[i]=0;
  75. doesntUsed.add(i+1);
  76. }
  77. stack.push(index);
  78. colors[a-1]=1;
  79. while (!(doesntUsed.isEmpty())){
  80. doesntUsed.remove(index);
  81. for (i=1; i<gr[index-1].neighbours.size()+1; i++){
  82. temp=gr[index-1].neighbours.get(i);
  83. if (colors[temp-1]==0){
  84. stack.push(temp);
  85. colors[temp-1]=1;
  86. //еще не были тут.
  87. } else {
  88. if (!doesntUsed.contains(temp)){
  89. return false;
  90. //цикл
  91. }else{
  92. //нет цикла, но тут были уже
  93. }
  94. }
  95. }
  96. index=stack.lastElement();
  97. }
  98. i=0;
  99. while (!(stack.isEmpty())){
  100. timeOfDeath[i]=stack.pop();
  101. i++;
  102. }
  103. return true;
  104. }
  105. }
Add Comment
Please, Sign In to add comment