标签:
Description
Input
Output
Sample Input
4 6 A<B A<C B<C C<D B<D A<B 3 2 A<B B<A 26 1 A<Z 0 0
Sample Output
Sorted sequence determined after 4 relations: ABCD. Inconsistency found after 2 relations. Sorted sequence cannot be determined.
1 #include<cstdio> 2 #include<cstring> 3 #include<vector> 4 using namespace std; 5 6 vector<int>G[27]; 7 int cnt; 8 char b[27]; 9 int m,n; 10 int c[27]; 11 bool mark[27][27]; 12 13 bool dfs(int u) 14 { 15 c[u]=-1; 16 for(int i=0;i<G[u].size();i++) 17 { 18 if(c[G[u][i]]<0) 19 return false; 20 else if(!c[G[u][i]]&&!dfs(G[u][i])) 21 return false; 22 } 23 b[--cnt]=u+‘A‘; 24 c[u]=1; 25 return true; 26 } 27 28 int toposort() 29 { 30 bool flag; 31 int i,j; 32 for(i=0;i<n;i++) 33 { 34 memset(c,0,sizeof(c)); 35 cnt=n; 36 flag=dfs(i); 37 if(!flag) 38 return -1; 39 else 40 { 41 for(j=0;j<n;j++) 42 if(!c[j])break; 43 if(j!=n)continue; 44 int k; 45 for(k=0;k<n-1;k++) 46 if(!mark[(int)b[k]-‘A‘][(int)b[k+1]-‘A‘]) 47 break; 48 if(k==n-1) 49 return 1; 50 } 51 } 52 return 0; 53 } 54 55 int main() 56 { 57 // freopen("in.txt","r",stdin); 58 while(scanf("%d%d",&n,&m),n|m) 59 { 60 memset(mark,0,sizeof(mark)); 61 bool key=false; 62 int i; 63 for(i=0;i<n;i++) 64 G[i].clear(); 65 for(i=0;i<m;i++) 66 { 67 char u,v; 68 getchar(); 69 scanf("%c<%c",&u,&v); 70 if(key) 71 continue; 72 if(!mark[u-‘A‘][v-‘A‘]) 73 { 74 G[(int)u-‘A‘].push_back((int)v-‘A‘); 75 mark[u-‘A‘][v-‘A‘]=1; 76 } 77 int ans=toposort(); 78 if(ans==1) 79 { 80 printf("Sorted sequence determined after %d relations: ",i+1); 81 for(int j=0;j<n;j++) 82 printf("%c",b[j]); 83 printf(".\n"); 84 key=true; 85 continue; 86 } 87 else if(ans==-1) 88 { 89 printf("Inconsistency found after %d relations.\n",i+1); 90 key=true; 91 continue; 92 } 93 } 94 if(!key) 95 printf("Sorted sequence cannot be determined.\n"); 96 } 97 return 0; 98 }
POJ 1094 Sorting It All Out(拓扑排序)
标签:
原文地址:http://www.cnblogs.com/homura/p/4814641.html