Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private class Node{
- HashSet<Integer> fromThis; //this -> neighbours
- HashSet<Integer> toThis; //neighbours -> this
- LinkedList<Integer> neighbours; //all vertexes from this
- Node(){
- fromThis=new HashSet<Integer>();
- toThis=new HashSet<Integer>();
- neighbours=new LinkedList<Integer>();
- }
- }
- private class Graph{
- private BufferedReader in;
- private PrintWriter out;
- private StringTokenizer st;
- private Stack<Integer> stack;
- private int colors[];
- private int timeOfDeath[];
- private HashSet<Integer> doesntUsed;
- private int vNum; //number of vertexes
- private int eNum; //number of edges
- private Node gr[];
- Graph(){
- vNum=0;
- eNum=0;
- }
- Graph(String arg)throws IOException{
- loadGraph(arg);
- }
- public boolean isEmpty(){
- return vNum==0;
- }
- private void addEdge(int a, int b){ //from a to b
- gr[a-1].fromThis.add(b);
- gr[b-1].fromThis.add(a);
- gr[a-1].neighbours.add(b);
- eNum++;
- }
- public void loadGraph(String arg)throws IOException{
- in=new BufferedReader(new FileReader(arg));
- String temp=in.readLine();
- st=new StringTokenizer(temp);
- vNum=Integer.parseInt(st.nextToken());
- int e=Integer.parseInt(st.nextToken());
- gr=new Node[vNum];
- int i;
- for (i=0; i<vNum; i++){
- gr[i] = new Node();
- }
- if (e>0){
- int a,b;
- for (i=0; i<e; i++){
- temp=in.readLine();
- st=new StringTokenizer(temp);
- a=Integer.parseInt(st.nextToken());
- b=Integer.parseInt(st.nextToken());
- addEdge(a, b);
- }
- }
- in.close();
- }
- public boolean topSort(int a){ //a- вершина с которой начинается...
- stack=new Stack<Integer>();
- colors=new int[vNum];
- doesntUsed=new HashSet<Integer>();
- timeOfDeath=new int[vNum];
- int i, index=a, temp;
- for (i=0; i<vNum; i++){
- colors[i]=0;
- doesntUsed.add(i+1);
- }
- stack.push(index);
- colors[a-1]=1;
- while (!(doesntUsed.isEmpty())){
- doesntUsed.remove(index);
- for (i=1; i<gr[index-1].neighbours.size()+1; i++){
- temp=gr[index-1].neighbours.get(i);
- if (colors[temp-1]==0){
- stack.push(temp);
- colors[temp-1]=1;
- //еще не были тут.
- } else {
- if (!doesntUsed.contains(temp)){
- return false;
- //цикл
- }else{
- //нет цикла, но тут были уже
- }
- }
- }
- index=stack.lastElement();
- }
- i=0;
- while (!(stack.isEmpty())){
- timeOfDeath[i]=stack.pop();
- i++;
- }
- return true;
- }
- }
Add Comment
Please, Sign In to add comment