Harry and Magical Computer

来源:互联网 发布:lol末日人工智能攻略 编辑:程序博客网 时间:2024/05/16 12:58

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.1n100,1m10000
The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b).1a,bn
 

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 23 12 13 33 22 11 3
 

Sample Output
YESNO题解:裸地拓扑排序,直接二维数组。
#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace std; const int INF = 0x3fffffff;bool map[103][103];int indegree[103];bool topoSort(int n){for(int i = 1;i <= n;i++){int k = -1;for(int j = 1;j <= n;j++){if(indegree[j] == 0){k = j;indegree[j]--;break;}}if(k == -1){return false;}for(int j = 1;j <= n;j++){if(map[k][j]){indegree[j]--;}}}return true;}int main(){int n,m;while(scanf("%d%d",&n,&m) != EOF){memset(indegree,0,sizeof(indegree));memset(map,false,sizeof(map));int u,v;for(int i = 0; i< m;i++){scanf("%d%d",&u,&v);if(!map[v][u]){map[v][u] = true;indegree[u]++;}}if(topoSort(n)){printf("YES\n");}else{printf("NO\n");}}return 0;}


0 0