HDU2647+拓扑排序
先判断是否存在环。。然后dfs出每个人比几个人要求高。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ///* 2 //拓扑 3 //*/ 4 #include<stdio.h> 5 #include<string.h> 6 const int maxn = 10105; 7 int ind[ maxn ],add[ maxn ],vis[ maxn ]; 8 struct node{ 9 int u,next; 10 }edge[ maxn<<2 ]; 11 int cnt,head[ maxn ]; 12 void init(){ 13 cnt = 0; 14 memset( add,0,sizeof( add ) ); 15 memset( head,-1,sizeof( head ) ); 16 memset( vis,0,sizeof( vis ) ); 17 memset( ind,0,sizeof( ind ) ); 18 } 19 void addedge( int a,int b ){ 20 edge[ cnt ].u = b; 21 edge[ cnt ].next = head[ a ]; 22 head[ a ] = cnt++; 23 } 24 25 int dfs( int cur ){ 26 if( vis[ cur ]!=0 ) return add[ cur ]; 27 //printf("cur=%d\n",cur); 28 vis[ cur ] = 1; 29 for( int i=head[ cur ];i!=-1;i=edge[ i ].next ){ 30 //printf("nxt=%d\n",edge[i].u); 31 int dis = dfs( edge[ i ].u ); 32 if( add[ cur ]<dis+1 ) add[ cur ] = dis+1; 33 } 34 return add[ cur ]; 35 } 36 37 int tuopu( int n ){ 38 int cnt = 0; 39 for( int i=1;i<=n;i++ ){ 40 int s = -1; 41 for( int j=1;j<=n;j++ ){ 42 if( ind[ j ]<-1){ 43 return -1; 44 } 45 if( ind[ j ]==0 ){ 46 ind[ j ] = -1; 47 s = j; 48 cnt++; 49 break; 50 } 51 } 52 //printf("s=%d\n",s); 53 if( s==-1 ) break; 54 for( int j=head[ s ];j!=-1;j=edge[ j ].next ){ 55 ind[ edge[j].u ]--; 56 if( ind[ edge[j].u ]<-1 ) return -1; 57 } 58 } 59 if( cnt==n ) return 1; 60 else return -1; 61 } 62 63 int main(){ 64 int n,m; 65 while( scanf("%d%d",&n,&m)==2 ){ 66 init(); 67 int a,b; 68 while( m-- ){ 69 scanf("%d%d",&a,&b); 70 ind[ b ]++; 71 addedge( a,b ); 72 } 73 74 int flag = tuopu( n ); 75 if( flag==-1 ){ 76 printf("-1\n"); 77 continue; 78 } 79 //printf("flag=%d\n",flag); 80 for( int i=1;i<=n;i++ ){ 81 if( vis[ i ]==0 ){ 82 dfs( i ); 83 } 84 } 85 int sum = n*888; 86 //printf("sum=%d\n",sum); 87 for( int i=1;i<=n;i++ ){ 88 sum+=add[i]; 89 //printf("add[%d]=%d\n",i,add[i]); 90 } 91 printf("%d\n",sum); 92 } 93 return 0; 94 }
keep moving...