Sorting It All Out
Time Limit: 1000MS |
Memory Limit: 10000K |
Total Submissions: 18506 |
Accepted: 6310 |
Description
An ascending sorted sequence of distinct values isone inwhich some form of a less-than operator is used to order theelements fromsmallest to largest. For example, the sorted sequenceA, B, C, D implies that A< B, B < Cand C < D. in this problem, we will give you a setofrelations of the form A < B and ask you todetermine whether a sorted orderhas been specified or not.
Input
Input consists of multiple problem instances.Eachinstance starts with a line containing two positive integers n andm. thefirst value indicated the number of objects to sort, where 2<= n <= 26.The objects to be sortedwill be the first n characters of the uppercasealphabet. Thesecond value m indicates the number of relations of the form A<B which will be given in this problem instance.Next will be m lines, eachcontaining one such relation consistingof three characters: an uppercaseletter, the character"<" and a second uppercase letter. No letterwill beoutside the range of the first n letters of the alphabet. Values ofn = m= 0 indicate end of input.
Output
For each problem instance, output consists of oneline.This line should be one of the following three:
Sorted sequence determined after xxx relations:yyy...y.
Sorted sequence cannot be determined.
Inconsistency found after xxx relations.
where xxx is the number of relations processed at the time either asortedsequence is determined or an inconsistency is found,whichever comes first, andyyy...y is the sorted, ascendingsequence.
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个字母的顺序
或者是存在环。在编写程序时首先要判断是不是有环,如果有,返回0,
如果存在多种情况,标记flag2为-1,然后继续进行判断有没有环,如果没有,返回-1;
如果没没出现上述情况,则返回1。
代码:
#include<stdio.h>
#include<string.h>
int n,m,j,i;
intmap[100][100],q,d[100],t[100];
int flag,flag1;
char a[100];
int ju[100];
int topo(){
int i,j,flag2=1,p,temp,k=0;
for(i=0;i<n;i++)
t[i]=d[i];
for(i=0;i<n;i++)
{
p=0;
for(j=0;j<n;j++)
if(t[j]==0)
{
p++;
temp=j;
}
if(p==0&&p!=n) return 0;
if(p>1) flag2=-1;
ju[k++]=temp;
t[temp]=-1;
for(j=0;j<n;j++)
if(map[temp][j]==1)
t[j]--;
}
return flag2;
}
int main(){
while(1){
scanf("%d %d",&n,&m);
flag1=0;
if(n==0&&m==0)
break;
memset(map,0,sizeof(map));
memset(d,0,sizeof(d));
for(i=0;i<m;i++)
{
scanf("%s",a);
map[a[0]-'A'][a[2]-'A']=1;
d[a[2]-'A']++;
if(flag1==0)
q=topo();
if(q==1&&flag1==0)
{
printf("Sorted sequencedetermined after %d relations: ",i+1);
for(j=0;j<n;j++)
printf("%c",ju[j]+'A');
printf(".n");
flag1=1;
}
if(q==0&&flag1==0)
{
printf("Inconsistency foundafter %d relations.n",i+1);
flag1=1;
}
}
if(flag1==0)
printf("Sorted sequence cannot bedetermined.n");
}
return 0;
}