标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5336 Accepted Submission(s): 1619
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 #define N 10005 6 #define M 20005 7 int in[N]; 8 int que[N]; 9 int my[N]; 10 struct Edge{ 11 int to ; 12 int next; 13 }edge[M]; 14 int head[N]; 15 int Enct; 16 void init() 17 { 18 Enct = 0; 19 memset(head,-1,sizeof(head)); 20 memset(my,0,sizeof(my)); 21 memset(in,0,sizeof(in)); 22 } 23 void add(int from, int to) 24 { 25 edge[Enct].to = to; 26 edge[Enct].next = head[from]; 27 head[from] = Enct++; 28 } 29 int c; 30 int t; 31 int n; 32 int tm ; 33 bool tp() 34 { 35 c = 0; 36 t = 1; 37 for(int i = 0 ;i < n ;i++) 38 { 39 if(in[i]==0) 40 { 41 que[c++] = i; 42 } 43 } 44 for(int i = 0 ;i < c ; i++) 45 { 46 int id = que[i]; 47 for(int j = head[id] ; j !=-1 ; j = edge[j].next) 48 { 49 int t = my[id]; 50 Edge e = edge[j]; 51 in[e.to]--; 52 my[e.to] = max(t+1,my[e.to]);//后继大于前驱,每次都要更新 53 if(in[e.to]==0) 54 { 55 que[c++] = e.to; 56 } 57 } 58 } 59 if(c<n) return false; 60 else return true; 61 } 62 int main() 63 { 64 int m ; 65 while(~scanf("%d%d",&n,&m)) 66 { 67 init(); 68 for(int i = 0 ;i < m ;i++) 69 { 70 int a , b; 71 scanf("%d%d",&a,&b); 72 add(b,a);//因为是前者比后者多,所以键反向边 73 in[b]++; 74 } 75 if(tp()==false) printf("-1\n"); 76 else 77 { 78 int sum = 0 ; 79 for(int i = 1;i <= n ;i++) 80 { 81 sum+=my[i]; 82 } 83 printf("%d\n",888*n+sum); 84 } 85 } 86 return 0; 87 }
标签:
原文地址:http://www.cnblogs.com/shanyr/p/4701005.html