1 // topological sort to determine whether there ring 2 #include <cstdio> . 3 #include <algorithm> . 4 #include < String .h> . 5 #include <math.h> . 6 #include <Queue> . 7 the using namespace STD; . 8 typedef Long Long LL; . 9 const int MAXN 1E2 + = 10 ; 10 int G [MAXN] [MAXN]; . 11 int in [MAXN]; 12 is void the init () 13 is { 14 Memset (G, 0 ,the sizeof (G)); // FIG. 15 Memset ( in , 0 , the sizeof ( in )); // Penetration 16 } . 17 int Toposort ( int n-) 18 is { . 19 int AIM; 20 is int COT = 0 ; 21 is int In Flag = 1 ; // 1 when an ordered 22 // every cycle, to identify the degree of zero point, if you can not find prove ring (this force memory) 23 // once located, this point the connected side of the other endpoint 1; 24 // the algorithm ends 25 for(int i=1;i<=n;i++){ 26 int num=0; 27 for(int j=1;j<=n;j++) 28 if(!in[j]){ 29 num++; 30 aim=j; 31 break; 32 } 33 if(!num) return 0; //有环; 34 in[aim]=-1; 35 for(int j=1;j<=n;j++) 36 if(G[aim][j]) in[j]--; 37 } 38 return flag; 39 40 } 41 int main() 42 { 43 int n,m; 44 while(scanf("%d%d",&n,&m)!=EOF){ 45 init(); //初始化 46 for(int i=1;i<=m;i++){ 47 int u,v; 48 Scanf ( " % D% D " , & U, & v); 49 G [U] [v] = . 1 ; 50 in [v] ++; // U v to v edged so that the penetration ++; 51 is } 52 is int In Flag = Toposort (n-); 53 is IF (In Flag == . 1 ) the printf ( " YES \ n- " ); 54 is the else the printf ( " NO \ n- " ); 55 } 56 is return 0 ; 57 is }
.