HDU3342(拓扑排序)

package D0731;

/*
 * 题目意思:
 * 判断师傅、徒弟关系的合法性:一个师傅可以有多个徒弟
 * 一个徒弟也可以有多个师傅
 * 但是a不能既是b的徒弟又是b的师傅。
 * 
 * 思路:拓扑排序。
 * */
//用邻接矩阵实现
import java.util.*;

public class HDU3342 {

	static int n, m;
	static int[][] G;// 邻接矩阵
	static int[] indegree;// 顶点的入度
	static Queue<Integer> que;
	static int index;//保存最后的结果,如果等于n表示合法,否则No

	private static void topSort() {
		que = new PriorityQueue<Integer>();
		index = 0;
		for (int i = 0; i < n; i++) {
			if (indegree[i] == 0)//入度为0的顶点入队
				que.add(i);
		}
		while (!que.isEmpty()) {
			int v = que.poll();//出队
			index++;
			for (int i = 0; i < n; i++) {//删除顶点v及以v为尾的弧。
				if (G[v][i] == 1) {
					indegree[i]--;
					if (indegree[i] == 0)
						que.add(i);
				}
			}
		}

	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			n = sc.nextInt();
			m = sc.nextInt();
			if (n == 0)
				break;
			G = new int[n][n];
			indegree = new int[n];
			while (m-- > 0) {
				int u = sc.nextInt();
				int v = sc.nextInt();
				if (G[u][v] == 0) {//注意重边
					G[u][v] = 1;
					indegree[v]++;
				}
			}
			topSort();
			if (index ==n)
				System.out.println("YES");
			else
				System.out.println("NO");
		}

	}

}


 

 

package D0731;
//用邻接表实现
import java.util.*;

public class HDU3342_2 {
	static int n, m;
	static int[] indegree;
	static int index;
	static List<ArrayList<Integer>>G;//邻接表
	static Queue<Integer> que;
	private static void topSort() {
		index = 0;
		que = new PriorityQueue<Integer>();
		for(int i = 0;i<n;i++)
			if(indegree[i]==0)que.add(i);
		while(!que.isEmpty()){
			int v = que.poll();
			index++;
			for(int i :G.get(v)){
				indegree[i]--;
				if(indegree[i]==0)que.add(i);
			}
		}

	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext()) {
			n = sc.nextInt();
			m = sc.nextInt();
			if (n == 0)
				break;
			indegree = new int[n];
			G = new ArrayList<ArrayList<Integer>>();
			for(int i = 0;i<n;i++)
				G.add(new ArrayList<Integer>());
			while (m-- > 0) {
				int u = sc.nextInt();
				int v = sc.nextInt();
				if (!G.get(u).contains(v)) {// 注意重边
					G.get(u).add(v);
					indegree[v]++;
				}
			}
			topSort();
			if (index == n)
				System.out.println("YES");
			else
				System.out.println("NO");
		}

	}

	
}



 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怎么演

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值