POJ 1094 Sorting It All Out
2016-05-29 12:05:01
题目链接: POJ 1094 Sorting It All Out
题目大意:
给出N个元素的M个严格不等关系(如:A<B).
判断:1.是否可以推出这N个元素的排列并输出是在前多少个关系中推出
2.关系中是否出现不合法的情况并输出是在前多少个关系中推出
解法:
判断关系环首先想到用拓扑排序
需要注意的地方
1.如果出现Topsort过程中有同时多个0度点,说明关系是不能确定的(无法说明这几个0度点的关系)
2.结果得出之后不再需要继续判断,但是一定要读入完整的数据QAQ
1 //Sorting It All Out (POJ No.1094) 2 //拓扑排序 3 #include<stdio.h> 4 #include<algorithm> 5 #include<string.h> 6 using namespace std; 7 const int maxn=30; 8 char now[5]; 9 int N,M; 10 int in[maxn],constin[maxn]; 11 int stack[maxn]; 12 int top; 13 int cnt; 14 int head[maxn]; 15 bool deleted[maxn]; 16 int ans[maxn]; 17 int Index; 18 bool finished; 19 struct edge 20 { 21 int to; 22 int next; 23 }; 24 edge n[maxn*maxn]; 25 void insert(int x,int y) 26 { 27 cnt++; 28 n[cnt].to=y; 29 n[cnt].next=head[x]; 30 head[x]=cnt; 31 return ; 32 } 33 int Topsort() 34 { 35 Index=0; 36 int now,sums=0,flag=0;; 37 fill(deleted,deleted+maxn,0); 38 for(int i=1;i<=N;i++) 39 { 40 in[i]=constin[i]; 41 sums+=in[i]; 42 } 43 for(int i=1;i<=N;i++) 44 { 45 if(!in[i]) 46 { 47 top++; 48 stack[top]=i; 49 } 50 } 51 while(top) 52 { 53 if(top>1)flag=1; 54 now=stack[top--]; 55 deleted[now]=1; 56 ans[++Index]=now; 57 for(int i=head[now];i;i=n[i].next) 58 { 59 if(!deleted[n[i].to]) 60 { 61 in[n[i].to]--; 62 sums--; 63 if(!in[n[i].to]) 64 { 65 stack[++top]=n[i].to; 66 } 67 } 68 } 69 } 70 if(sums)return 0; 71 else if(!flag)return 1; 72 else return 2; 73 } 74 int main() 75 { 76 while(1) 77 { 78 scanf("%d %d",&N,&M); 79 if(N==0&&M==0)break; 80 finished=0;cnt=0; 81 fill(head,head+maxn,0); 82 fill(constin,constin+maxn,0); 83 for(int i=1;i<=M;i++) 84 { 85 scanf("%s",now); 86 if(!finished) 87 { 88 insert(now[0]-'A'+1,now[2]-'A'+1); 89 constin[now[2]-'A'+1]++; 90 int tmp=Topsort(); 91 if(tmp==0) 92 { 93 printf("Inconsistency found after %d relations.\n",i); 94 finished=1; 95 } 96 else if(tmp==1&&Index==N) 97 { 98 printf("Sorted sequence determined after %d relations: ",i); 99 for(int i=1;i<=N;i++) 100 { 101 printf("%c",ans[i]-1+'A'); 102 } 103 printf(".\n"); 104 finished=1; 105 } 106 if(i==M&&finished==0)printf("Sorted sequence cannot be determined.\n"); 107 } 108 } 109 } 110 return 0; 111 }