hdoj-2647-Reward(拓扑排序)
1 /* 2 Name:hdoj-2647-Reward 3 Copyright: 4 Author: 5 Date: 2018/4/11 15:59:18 6 Description: 7 */ 8 #include <iostream> 9 #include <queue> 10 #include <vector> 11 #include <cstring> 12 #include <algorithm> 13 using namespace std; 14 const int MAXN = 1e+5; 15 int du[MAXN], n , m, L[MAXN]; 16 vector<int> g[MAXN]; 17 bool topsort() { 18 memset(du, 0, sizeof(du)); 19 for (int i=0; i<n; i++) { 20 for (int j=0; j<g[i].size(); j++) { 21 du[g[i][j]]++; 22 } 23 } 24 int tot = 0; 25 queue<int> Q; 26 for (int i=0; i<n; i++) { 27 if (!du[i]) { 28 Q.push(i); 29 L[i] = 0; 30 } 31 } 32 while (!Q.empty()) { 33 int x = Q.front(); 34 Q.pop(); 35 tot++; 36 for (int j=0; j<g[x].size(); j++) { 37 int t = g[x][j]; 38 du[t]--; 39 if (!du[t]) { 40 Q.push(t); 41 L[g[x][j]] = L[x] + 1; 42 } 43 } 44 } 45 if (tot == n) return 1; 46 return 0; 47 } 48 int main() 49 { 50 // freopen("in.txt", "r", stdin); 51 while (cin>>n>>m && (m || n)) { 52 memset(L, 0, sizeof(L)); 53 memset(g, 0, sizeof(g)); 54 for (int i=0; i<m; i++) { 55 int a, b; 56 cin>>a>>b; 57 a--; 58 b--; 59 g[b].push_back(a); 60 } 61 if (topsort() == 1) { 62 int sum = 0; 63 for (int i=0; i<n; i++) { 64 sum += L[i]; 65 } 66 cout<<sum+n*888<<endl; 67 } 68 else cout<<"-1"<<endl; 69 } 70 return 0; 71 }