拓扑序列 之 hdu 5154 Harry and Magical Computer

/*
AOV网(Activity On Vertex Network):
	用图来表示工程:其中,用顶点表示活动;弧表示活动之间的制约关系。
 
工程是否顺利进行?---->AOV网是否存在有向回路
 
*******************************************
用产生(包含所有) 顶点序列的方法,顶点序列满足:
	在图中,若顶点vi到顶点vj存在路径,
	则在序列中,顶点vi领先于顶点vj。
满足上述条件的顶点序列称为拓扑序列,
产生这一序列的过程称为拓扑排序。
*******************************************
 
AOV网是否含有有向回路 <----> 是否可以产生拓扑序列
 
 
注意:
此题测试数据中,对于重边,保存一条即可;对于自环也需要输出"NO"。
 
*/
  1 #include <iostream>
  2 #include <cstdlib>
  3 #include <cstdio>
  4 #include <cstddef>
  5 #include <iterator>
  6 #include <algorithm>
  7 #include <string>
  8 #include <locale>
  9 #include <cmath>
 10 #include <vector>
 11 #include <cstring>
 12 #include <map>
 13 #include <utility>
 14 #include <queue>
 15 #include <stack>
 16 #include <set>
 17 #include <functional>
 18 using namespace std;
 19 typedef pair<int, int> PII; 
 20 typedef long long int64;
 21 const int INF = 0x3f3f3f3f;
 22 const int modPrime = 3046721;
 23 const double eps = 1e-9;
 24 const int MaxN = 110;
 25 const int MaxM = 10010;
 26 
 27 int n, m;
 28 bool G[MaxN][MaxN];
 29 int ndCnt[MaxN];
 30 
 31 
 32 void Solve()
 33 {
 34     int cnt = 0;
 35     stack<int> stk;
 36     for (int i = 0; i < n; ++i)
 37     {
 38         if (0 == ndCnt[i])
 39         {
 40             stk.push(i);
 41         }
 42     }
 43     while (!stk.empty())
 44     {
 45         int node = stk.top();
 46         stk.pop();
 47         ++cnt;
 48         for (int i = 0; i < n; ++i)
 49         {
 50             if (G[node][i])
 51             {
 52                 --ndCnt[i];
 53                 if (0 == ndCnt[i])
 54                 {
 55                     stk.push(i);
 56                 }
 57             }
 58         }
 59     }
 60     if (cnt == n)
 61     {
 62         printf("YES\n");
 63     }
 64     else
 65     {
 66         printf("NO\n");
 67     }
 68 }
 69 
 70 int main()
 71 {
 72 #ifdef HOME
 73     freopen("in", "r", stdin);
 74     //freopen("out", "w", stdout);
 75 #endif
 76     while (~scanf("%d %d", &n, &m))
 77     {
 78         for (int i = 0; i < n; ++i)
 79         {
 80             ndCnt[i] = 0;
 81             for (int j = 0; j < n; ++j)
 82             {
 83                 G[i][j] = false;
 84             }
 85         }
 86 
 87         int a, b;
 88         for (int i = 0; i < m; ++i)
 89         {
 90             scanf("%d %d", &a, &b);
 91             // 对于重边的处理办法
 92             if (!G[b - 1][a - 1])
 93             {
 94                 G[b - 1][a - 1] = true;
 95                 ++ndCnt[a - 1];
 96             }
 97         }
 98         Solve();
 99     }
100 
101 #ifdef HOME
102     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
103     _CrtDumpMemoryLeaks();
104 #endif
105     return 0;
106 }

 

 
posted @ 2015-12-17 19:53  JmingS  阅读(142)  评论(0编辑  收藏  举报