[SSL] 1129 alphabetical order
Time Limit:1000MS
Memory Limit:65536K
Description
Enter a series of letters that are less than the relationship and output the final order. For
example, enter: A
Input
Two integers nm (2<=n<=26) (end when n=m=0)
m line "less than relation" (only less than<)
Output
If the last sorting exists, output: Sorted sequence determined after xxx relations: yyy...y.
If the sorting cannot be completed, output: Sorted sequence cannot be determined.
If there is a contradiction after the xth relationship (such as A<B,B<C, C<A) Output: Inconsistency found after x relations.
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.
Hint
uncle
Ideas
It is a multi-group data version sorted by P1347 in 【Luogu】 , the initial value should be set each time.
For each input, do a topological sort.
Conflicts output
. Inconsistency found after x relations
sorting the only output
Sorted sequence determined after xxx relations: yyy ... y.
Code
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
long long ans[610],tot,n,m,head[610],ins[610],inst[610],q[610];
char str[610];
string answer;
struct jgt
{
long long x,y,nxt;
}f[610];
int topsort()
{
long long i,l,r=0;
for(i=1;i<=n;i++)
if(!inst[i])
{
q[++r]=i;
ans[i]=1;
}
for(l=1;l<=r;l++)
{
for(i=head[q[l]];i;i=f[i].nxt)//更新入度
{
inst[f[i].y]--;
ans[f[i].y]=max(ans[f[i].y],ans[q[l]]+1);
if(!inst[f[i].y])//当能够到达这个点的所有点都遍历过后将这个点加入队列
q[++r]=f[i].y;
}
}
if(r<n)//矛盾
return 0;
if(ans[q[r]]==n)//排序唯一
{
for(i=1;i<=r;i++)
answer+=char(q[i]+'A'-1);
return 1;
}
return -1;
}
int main()
{
long long i,j,t;
bool light;
scanf("%lld%lld",&n,&m);
while(n||m)
{
tot=0;
light=1;
answer="";
memset(ins,0,sizeof(ins));
memset(head,0,sizeof(head));
memset(ans,0,sizeof(ans));
memset(inst,0,sizeof(inst));
memset(q,0,sizeof(q));
for(i=1;i<=m;i++)
{
tot++;
scanf("%s",&str);
f[tot].x=str[0]-'A'+1;
f[tot].y=str[2]-'A'+1;
f[tot].nxt=head[f[tot].x];
head[f[tot].x]=tot;
ins[f[tot].y]++;
for(j=1;j<=n;j++)
inst[j]=ins[j];
t=topsort();
if(t==0)
{
printf("Inconsistency found after %lld relations.\n",i);
light=0;
for(i++;i<=m;i++)scanf("%*s");
}
if(t==1)
{
printf("Sorted sequence determined after %lld relations: %s.\n",i,answer.c_str());
light=0;
for(i++;i<=m;i++)scanf("%*s");
}
}
if(light)
printf("Sorted sequence cannot be determined.\n");
scanf("%lld%lld",&n,&m);
}
return 0;
}