拓扑图,用于判断有向图是否有环 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);
			}
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值