题意是个大坑。。。只要,保证有且只有一个人的入度是0,就yes。。
1 #include<stdio.h> 2 #include<string> 3 #include<map> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 const int maxn = 2005; 8 int ind[ maxn ]; 9 struct node{ 10 int u,next; 11 }edge[ maxn*2000 ]; 12 int cnt,head[ maxn ]; 13 map<string,int>mp; 14 int vis[ maxn ]; 15 void init(){ 16 mp.clear(); 17 memset( vis,0,sizeof( vis ) ); 18 memset( ind,0,sizeof( ind ) ); 19 memset( head,-1,sizeof( head ) ); 20 cnt = 0; 21 } 22 void addedge( int a,int b ){ 23 edge[ cnt ].u = b; 24 edge[ cnt ].next = head[ a ]; 25 head[ a ] = cnt++; 26 } 27 28 void tuopu( int n ){ 29 //printf("tuopu\n"); 30 int sum = 0; 31 for( int i=1;i<=n;i++ ){ 32 int s = -1; 33 for( int j=1;j<=n;j++ ){ 34 if( ind[j]==0 ){ 35 s = j; 36 sum++; 37 ind[ j ] = -1; 38 break; 39 } 40 if( ind[ j ]<0 ){ 41 sum = -1; 42 break; 43 } 44 } 45 if( s==-1||sum==-1 ) break; 46 for( int j=head[ s ];j!=-1;j=edge[ j ].next ){ 47 ind[ edge[ j ].u ]--; 48 if( ind[ edge[ j ].u ]<0 ){ 49 sum = -1; 50 break; 51 } 52 } 53 if( sum==-1 ) break; 54 } 55 if( sum<n||sum>n ) printf("No\n"); 56 else printf("Yes\n"); 57 } 58 59 int main(){ 60 int n; 61 while( scanf("%d",&n)==1,n ){ 62 init(); 63 int cc = 1; 64 int num1,num2; 65 string a,b; 66 while( n-- ){ 67 cin>>a>>b; 68 if( mp[a]==0 ){ 69 mp[a]=cc; 70 num1 = cc++; 71 } 72 else num1 = mp[a]; 73 if( mp[b]==0 ){ 74 mp[b]=cc; 75 num2 = cc++; 76 } 77 else num2 = mp[b]; 78 ind[ num2 ]++; 79 addedge( num1,num2 ); 80 } 81 int sum = 0; 82 //int k; 83 for( int i=1;i<cc;i++ ){ 84 if( ind[i]==0 ){ 85 sum++; 86 //k = i; 87 if( sum>=2 ) 88 break; 89 } 90 } 91 if( sum>=2 ){ 92 printf("No\n"); 93 continue; 94 } 95 if( sum==1 ){ 96 printf("Yes\n"); 97 continue; 98 } 99 tuopu( cc-1 ); 100 } 101 return 0; 102 }