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");
}
}
}