拓扑图,用于判断有向图是否有环 HDOJ 3342

拓扑图参考链接:https://blog.csdn.net/qq_41713256/article/details/80805338
进行判断是否有环,则就是判断两个点之间是否连接,如果互相都连接的话,则它们之间存在对方的参数。
用于解决题目:http://acm.hdu.edu.cn/showproblem.php?pid=3342
以下为topSort的代码:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

public class TopSort {
//判断有向图是否有环
	static ArrayList<ArrayList<Integer>> al; 
	//static Map<Integer,Integer> sum;//用于存放每个子节点有几个头结点与他相连
	static int[] uper;
	static Stack<Integer> st;
	static int m;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		while(true) {
		m = sc.nextInt();//结点数
		int n =sc.nextInt();//关系
		if(m==0&&n==0)
			break;
		uper = new int[m];
		st=new Stack();
		al = new ArrayList<ArrayList<Integer>>();
		int t=n;
		for(int i=0;i<m;i++) {
			al.add(new ArrayList<Integer>());
		}
		//System.out.println(t);
		while(t-->0) {
			int a =sc.nextInt();
			int b = sc.nextInt();
			if(!al.get(a).contains(b)) {
				//没有存在a->b这种关系,则存
				al.get(a).add(b);
				uper[b]++;//表示b有几个指向它
			}
			
		}
		int count=0;
		topSort();
		while(!st.isEmpty()) {
			count++;//用于判断有几个结点已经被弾栈了,不再出现了
			int ant=st.pop();//弾栈,弹出头结点
			uper[ant]--;
			int size = al.get(ant).size();//ant这个头结点指向的全部子节点
			for(int i=0;i<size;i++) {
				uper[al.get(ant).get(i)]--;//表示的是此结点的头结点失去了ant这个结点
			}
			topSort();
		}
		if(count==m) {
			//表示此时弹出的栈和总人数正好是一样的
			System.out.println("YES");//没有环
		}
		else {
			System.out.println("NO");//有环
		}
		}
	}
	private static void topSort() {
		// TODO Auto-generated method stub
		st.clear();
		for(int i=0;i<m;i++) {
			if(uper[i]==0) {//表面没有结点是指向它的了
				st.add(i);
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/So_Band/article/details/88758209