uestc 方老师的分身 III 拓扑排序

没什么好说的。。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<string>
 6 #include<queue>
 7 #include<algorithm>
 8 #include<map>
 9 #include<iomanip>
10 #include<climits>
11 #include<string.h>
12 #include<cmath>
13 #include<stdlib.h>
14 #include<vector>
15 #define INF 1e7
16 #define MAXN 100010
17 #define maxn 1000010
18 #define Mod 1000007
19 #define N 1010
20 using namespace std;
21 typedef long long LL;
22 
23 int n, m;
24 int son[10001];
25 int ans[10001];
26 
27 void init()
28 {
29     memset(son,0,sizeof(son));
30     memset(ans,0,sizeof(ans));
31 }
32 
33 void process()
34 {
35     vector<int> G[10010];
36     int x, y;
37     init();
38     for (int i = 0; i < m; ++i) {
39         cin >> x >> y;
40         G[y].push_back(x);
41         son[x]++;
42     }
43     queue<int> q;
44     for (int i = 1; i <= n; ++ i)
45         if (son[i] == 0){
46             q.push(i);
47             ans[i] = 888;
48         }
49     int res = n;
50     while (!q.empty()) {
51         int t = q.front();
52         q.pop();
53         res--;
54         for (int i = 0; i < G[t].size(); ++i) {
55             int v = G[t][i];
56             if (--son[v] == 0) {
57                 ans[v] = ans[t] + 1;
58                 q.push(v);
59             }
60         }
61     }
62     if (res > 0) puts("-1");
63     else {
64         int sum = 0;
65         for (int i = 1; i <= n; ++i)
66             sum += ans[i];
67         cout << sum << endl;
68     }
69 }
70 
71 int main()
72 {
73     while (cin >> n >> m)
74         process();
75     return 0;
76 }

 

posted @ 2015-02-14 00:18  UsedRose  阅读(152)  评论(0编辑  收藏  举报