【HDOJ】5154 Harry and Magical Computer

拓扑排序。

 1 /* 5154 */
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <queue>
 7 #include <vector>
 8 using namespace std;
 9 
10 #define MAXN 105
11 
12 vector<int> vec[MAXN];
13 vector<int>::iterator iter;
14 int cnt[MAXN];
15 int n, m;
16 
17 void init() {
18     int i;
19     
20     memset(cnt, 0, sizeof(cnt));
21     for (i=1; i<=n; ++i)
22         vec[i].clear();
23 }
24 
25 bool topSort() {
26     int i, j, k, tmp;
27     int c = 0;
28     queue<int> Q;
29     
30     for (i=1; i<=n; ++i) {
31         if (cnt[i] == 0) {
32             Q.push(i);
33         }
34     }
35     
36     while (!Q.empty()) {
37         ++c;
38         i = Q.front();
39         Q.pop();
40         for (iter=vec[i].begin(); iter!=vec[i].end(); ++iter) {
41             if (--cnt[*iter] == 0) {
42                 Q.push(*iter);
43             }
44         }
45     }
46     
47     if (c < n)
48         return false;
49     else
50         return true;
51 }
52 
53 int main() {
54     int i, j, k;
55     bool flag;
56     
57     #ifndef ONLINE_JUDGE
58         freopen("data.in", "r", stdin);
59     #endif
60     
61     while (scanf("%d %d", &n, &m) != EOF) {
62         init();
63         for (i=0; i<m; ++i) {
64             scanf("%d %d", &j, &k);
65             vec[j].push_back(k);
66             ++cnt[k];
67         }
68         flag = topSort();
69         if (flag)
70             printf("YES\n");
71         else
72             printf("NO\n");
73     }
74     
75     return 0;
76 }

 

posted on 2015-01-04 19:35  Bombe  阅读(157)  评论(0编辑  收藏  举报

导航