Legal or Not HDU - 3342 (拓扑排序)
注意点: 输入数据中可能有重复,需要进行处理!
1 #include <stdio.h> 2 #include <iostream> 3 #include <cstring> 4 #include <vector> 5 #include <algorithm> 6 #include <sstream> 7 8 9 using namespace std; 10 11 int n, m; 12 13 int indegree[101]; 14 int g[101][101]; 15 16 int main() 17 { 18 while(scanf("%d %d", &n, &m) != EOF) 19 { 20 if(n == 0 && m == 0) 21 break; 22 23 memset(indegree, 0, sizeof(indegree)); 24 memset(g, 0, sizeof(g)); 25 26 int a, b; 27 for(int i = 1; i <= m; ++i) 28 { 29 scanf("%d %d", &a, &b); 30 31 if(g[a][b] == 0) // 输入中有可能有反复输入如1,2;1,2这种情况!!! 32 { 33 g[a][b] = 1; 34 indegree[b]++; 35 } 36 37 } 38 39 int cnt = 0; 40 41 for(int k = 0; k < n; ++k) 42 { 43 int i, j; 44 for(i = 0; i < n; ++i) 45 { 46 if(indegree[i] == 0) 47 { 48 indegree[i] = -1; 49 cnt++; 50 break; 51 } 52 } 53 54 for(j = 0; j < n; ++j) 55 { 56 if(g[i][j] == 1) 57 { 58 indegree[j]--; 59 g[i][j] == 0; 60 } 61 } 62 } 63 64 65 if(cnt == n) 66 cout << "YES" << endl; 67 else 68 cout << "NO" << endl; 69 } 70 71 return 0; 72 }