拓撲排序,作的時候wa了n次,後來找來數據,又想了想,發現了本身的錯誤,就是當拓撲排序的時候出現了不肯定的狀況,還要在拓撲下去,由於可能還會有矛盾的狀況出現,保證沒矛盾的狀況下才能夠說是不肯定的狀況ios
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 using namespace std; 6 const int maxn=30; 7 int e[maxn*maxn],head[maxn],next[maxn*maxn],in[maxn],in2[maxn]; 8 int n,m,tot,path[maxn]; 9 int solve() 10 { 11 int i; 12 int top=0; 13 int sta[maxn]; 14 for(i=0;i<n;i++) 15 { 16 if(!in[i]) 17 sta[top++]=i; 18 } 19 int j,v; 20 int flag=1; 21 int tem; 22 for(i=0;i<n;i++) 23 { 24 if(top==0) return 0; 25 if(top>1) flag=-1; 26 tem=sta[--top]; 27 path[i]=tem; 28 for(j=head[tem];j!=-1;j=next[j]) 29 { 30 v=e[j]; 31 in[v]--; 32 if(in[v]==0) sta[top++]=v; 33 } 34 } 35 return flag; 36 } 37 int main() 38 { 39 // freopen("1.txt","r",stdin); 40 // freopen("2.txt","w",stdout); 41 while(scanf("%d%d",&n,&m)) 42 { 43 if(!n&&!m) break; 44 int i; 45 char s[4]; 46 tot=0; 47 memset(head,-1,sizeof(head)); 48 memset(in2,0,sizeof(in2)); 49 int ans; 50 int j; 51 for(i=0;i<m;i++) 52 { 53 scanf("%s",s); 54 s[0]-='A';s[2]-='A'; 55 in2[s[2]]++; 56 for(j=0;j<n;j++) in[j]=in2[j]; 57 e[tot]=s[2]; 58 next[tot]=head[s[0]]; 59 head[s[0]]=tot++; 60 ans=solve(); 61 if(ans==1||ans==0) break; 62 } 63 if(i<m) 64 { 65 for(j=i+1;j<m;j++) scanf("%s",s); 66 if(ans==1) 67 { 68 printf("Sorted sequence determined after %d relations: ",i+1); 69 for(j=0;j<n;j++) printf("%c",path[j]+'A'); 70 } 71 else printf("Inconsistency found after %d relations",i+1); 72 } 73 else printf("Sorted sequence cannot be determined"); 74 printf(".\n"); 75 } 76 return 0; 77 }