BC Harry and Magical Computer (拓扑排序)
Harry and Magical Computer
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.
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 one line for each test case. If the computer can finish all the process print "YES" (Without quotes). Else print "NO" (Without quotes).
3 2 3 1 2 1 3 3 3 2 2 1 1 3
YES NO
拓扑排序模板题。注意在处理IN[i] ++的时候要先判断是否已经存在这条边。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <cctype> 6 #include <cmath> 7 #include <queue> 8 #include <map> 9 #include <cstdlib> 10 using namespace std; 11 12 const int SIZE = 105; 13 int IN[SIZE]; 14 bool G[SIZE][SIZE]; 15 int N,M; 16 17 bool toposort(void); 18 int main(void) 19 { 20 int from,to; 21 22 while(scanf("%d%d",&N,&M) != EOF) 23 { 24 fill(IN,IN + SIZE,0); 25 fill(&G[0][0],&G[SIZE - 1][SIZE - 1],false); 26 for(int i = 0;i < M;i ++) 27 { 28 scanf("%d%d",&from,&to); 29 if(!G[from][to]) 30 IN[to] ++; 31 G[from][to] = 1; 32 } 33 if(toposort()) 34 puts("YES"); 35 else 36 puts("NO"); 37 } 38 39 return 0; 40 } 41 42 bool toposort(void) 43 { 44 int count = 0; 45 queue<int> que; 46 47 for(int i = 1;i <= N;i ++) 48 if(!IN[i]) 49 que.push(i); 50 51 while(!que.empty()) 52 { 53 int cur = que.front(); 54 que.pop(); 55 count ++; 56 57 for(int i = 1;i <= N;i ++) 58 if(G[cur][i]) 59 { 60 IN[i] --; 61 if(!IN[i]) 62 que.push(i); 63 } 64 } 65 if(count < N) 66 return false; 67 return true; 68 }