标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5863 Accepted Submission(s):
1797
1 #include <queue> 2 #include <cstdio> 3 #include <cstring> 4 #include <iostream> 5 using namespace std; 6 int indegree[10010], mon[10010]; 7 int n, m; 8 struct Edge 9 { 10 int from, to, next; 11 } edge[20020]; 12 int head[10010], cnt; 13 void Add(int a, int b) 14 { 15 Edge E = {a, b, head[a]}; 16 edge[cnt] = E; 17 head[a] = cnt++; 18 } 19 int sum; 20 void Tsort() 21 { 22 sum = 0; 23 queue<int> q; 24 for(int i = 1; i <= n; i++){ 25 if(!indegree[i]) 26 q.push(i); 27 mon[i] = 888; 28 } 29 while(!q.empty()) 30 { 31 int u = q.front(); 32 q.pop(); indegree[u]--; sum++; 33 for(int i = head[u]; i != -1; i = edge[i].next) 34 { 35 if(!--indegree[edge[i].to]) 36 mon[edge[i].to] = mon[u] + 1, q.push(edge[i].to); 37 } 38 } 39 int total = 0; 40 if(sum == n) 41 { 42 for(int i = 1; i <= n; i++) 43 total += mon[i]; 44 printf("%d\n", total); 45 } 46 else 47 printf("-1\n"); 48 } 49 int main() 50 { 51 while(~scanf("%d %d", &n, &m)) 52 { 53 cnt = 0; 54 memset(head, -1, sizeof(head)); 55 memset(indegree, 0, sizeof(indegree)); 56 for(int i = 1; i <= m; i++) 57 { 58 int a, b; 59 scanf("%d %d", &a, &b); 60 indegree[a]++; 61 Add(b, a); 62 } 63 Tsort(); 64 } 65 return 0; 66 }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/4743928.html