Harry and Magical Computer
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1743 Accepted Submission(s): 684
Problem Description
In reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins to deal with a process, it will work until the ending of the processes. One day the computer got n processes to deal with. We number the processes from 1 to n. However there are some dependencies between some processes. When there exists a dependencies (a, b), it means process b must be finished before process a. By knowing all the m dependencies, Harry wants to know if the computer can finish all the n processes.
Input
There are several test cases, you should process to the end of file.
For each test case, there are two numbers n m on the first line, indicates the number processes and the number of dependencies.
1≤n≤100,1≤m≤10000
The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b).
1≤a,b≤n
Output
Output one line for each test case.
If the computer can finish all the process print "YES" (Without quotes).
Else print "NO" (Without quotes).
Sample Input
3 2 3 1 2 1 3 3 3 2 2 1 1 3
Sample Output
Source
BestCoder Round #25
问题描述
作为年度优秀魔法学员的奖赏,哈利得到了一台具有魔力的计算机。这台计算机一旦开始处理某个任务,就会一直处理到这个任务结束为止(所以你可以认为它是单线程的)。有一天,这台计算机得到了n个任务要处理,分别标号1到n。这n个任务之间又有一些依赖关系,假如存在依赖关系(a, b),那么要处理a任务,必须先将b任务完成。现在哈利得到了所有的这些依赖关系,一共m个。他想知道,这台计算机能否完成所有的任务。
输入描述
多组输入数据
每组数据第一行由n m组成,分别代表任务数和依赖关系数。1 \leq n \leq 100, 1 \leq m \leq 100001≤n≤100,1≤m≤10000
接下来m行,每行两个数a b,表示一组依赖关系。1 \leq a, b \leq n1≤a,b≤n
输出描述
每组输出一行,"YES"(没有引号)表示能完成所有任务。
"NO"(没有引号)表示不能。
输入样例
3 2
3 1
2 1
3 3
3 2
2 1
1 3
输出样例
YES
NO
解题思路:如果存在任务不能完成,那么说明该任务既出现在某任务的前面又出现在某任务的后面,换句话说就是某些任务与该任务一起组成了一个环。用弗洛伊德算法,判断最后的邻接矩阵的对角线是否有1存在,如果有,说明存在环,否则没有。
代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include