【Luogu】P1347 Sort
Title description
An ascending sequence of different values refers to a sequence with elements increasing from left to right. For example, an ordered sequence of A, B, C, D means A<B, B<C, C<D. In this question, we will give you a series of relations in the form of A<BA<B, and ask you to judge whether you can determine the order of the sequence based on these relations.
Input format
In the first line, there are two positive integers n, m representing the number of elements to be sorted, 2≤n≤26, and the first to n elements will be represented by uppercase A, B, C, D... m represents the number of relations of the form A<B that will be given.
Next, there are m lines, each line has 3 characters, one uppercase letter, one <symbol, and one uppercase letter, indicating the relationship between the two elements.
Output format
If the order of the n elements can be determined according to the first x relations, yyy...y (such as ABC), output
Sorted sequence determined after xxx relations: yyy…y.
If a contradiction is found based on the first x relationships (such as A<B, B<C, C<A), output
Inconsistency found after x relations.
If the order of these n elements cannot be determined based on these m relations, output
Sorted sequence cannot be determined.
(Hint: the program can be ended after determining the sequence of n elements, and there is no need to consider the conflicts after the sequence is determined)
Ideas
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=0,n,m,head[610],ins[610],inst[610],q[610];
char str[610];
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++)
str[i-1]=q[i]+'A'-1;
return 1;
}
return -1;
}
int main()
{
long long i,j,t;
memset(ins,0,sizeof(ins));
scanf("%lld%lld",&n,&m);
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 %d relations.",i);
return 0;
}
if(t==1)
{
printf("Sorted sequence determined after %d relations: %s.",i,str);
return 0;
}
}
printf("Sorted sequence cannot be determined.");
return 0;
}