标签:
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 32966 | Accepted: 11458 |
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.
题目大意:给你n个大写字母,和m组字母相互之间的大小关系,让你判断在哪一次能够将所有字母
排好序,又或者在哪一次给出的关系与前面矛盾,即构成环了,否则就不能判断
思路:利用拓扑排序,如果能够排序,那么入度为0的点只可能有一个,否则就不知道选择哪一个在前
如果所有的点不能全部进行出栈排序,说明一定形成环了
注意:在拓扑排序时一定要注意判断顺序,就因为这个WA了好多次
代码如下:
1 #include <iostream> 2 #include<cstdio> 3 #include<stack> 4 #include<cstring> 5 using namespace std; 6 int n,m; 7 char str[4]; 8 int degree[27],A[27][27];//入度,以及邻接矩阵 9 char letter[27];//存储排序好的字母 10 int topSort() 11 { 12 //如果能够排序,那么肯定入度为0的点只有一个,有多个则不能确定选择哪一个 13 stack<int> st; 14 int temp[27],flag=0; 15 memcpy(temp,degree,sizeof(degree)); 16 for(int i=1;i<=n;i++) 17 if(temp[i]==0) 18 st.push(i);//找到入度为0的点 19 int index=0,cur; 20 while(!st.empty()) 21 { 22 if(st.size()>1)//入度为0点有多个,不能唯一排序 23 flag=1; 24 cur = st.top(); 25 st.pop(); 26 letter[index++]=cur+‘A‘-1; 27 for(int i=1;i<=n;i++) 28 if(A[cur][i]==1) 29 { 30 temp[i]--; 31 if(temp[i]==0) 32 st.push(i);//找到入度为0的点 33 } 34 } 35 if(index<n) 36 return 0;//有环 37 if(flag) 38 return -1; 39 return 1;//排序成功 40 41 } 42 int main() 43 { 44 freopen("in1.txt","r",stdin); 45 while(scanf("%d%d",&n,&m)!=EOF&&n) 46 { 47 bool sucess=false; 48 int flag=-1,time=0; 49 memset(degree,0,sizeof(degree)); 50 memset(A,0,sizeof(A)); 51 memset(letter,0,sizeof(letter)); 52 if(m==0&&n==1) 53 { 54 printf("Sorted sequence determined after 0 relations: A.\n"); 55 continue; 56 } 57 for(int i=1;i<=m;i++) 58 { 59 scanf("%s",str); 60 if(sucess) 61 continue; 62 int x = str[0]-‘A‘+1; 63 int y = str[2]-‘A‘+1; 64 degree[y]++;//入度加1 65 A[x][y]=1;//表示x邻接y 66 int flag1 = topSort(); 67 if(flag1==0) 68 { 69 flag=0;time=i; 70 sucess=true; 71 } 72 if(flag1==1) 73 { 74 flag=1;time=i; 75 sucess=true; 76 } 77 78 } 79 if(flag==-1) 80 printf("Sorted sequence cannot be determined.\n"); 81 else if(flag==0) 82 printf("Inconsistency found after %d relations.\n",time); 83 else 84 { 85 printf("Sorted sequence determined after %d relations: ",time); 86 for(int j=0;j<n;j++) 87 printf("%c",letter[j]); 88 printf(".\n"); 89 } 90 } 91 return 0; 92 }
标签:
原文地址:http://www.cnblogs.com/wt20/p/5750828.html