题目描述
一个不同的值的升序排序数列指的是一个从左到右元素依次增大的序列,例如,一个有序的数列A,B,C,DA,B,C,DA,B,C,D 表示A<B,B<C,C<DA<B,B<C,C<DA<B,B<C,C<D。在这道题中,我们将给你一系列形如A<B的关系,并要求你判断是否能够根据这些关系确定这个数列的顺序。
输入格式
第一行有两个整数n,m,nn,m,nn,m,n表示需要排序的元素数量,2<=n<=262<=n<=262<=n<=26,第111到nnn个元素将用大写的A,B,C,D…A,B,C,D…A,B,C,D…表示。m表示将给出的形如A<B的关系的数量。
接下来有mmm行,每行有333个字符,分别为一个大写字母,一个<符号,一个大写字母,表示两个元素之间的关系。
输出格式
若根据前xxx个关系即可确定这n个元素的顺序yyy…yyyy…yyyy…y(如ABCABCABC),输出
SortedSortedSorted sequencesequencesequence determineddetermineddetermined afterafterafter xxxxxxxxx relations:relations:relations: yyy…y.yyy…y.yyy…y.
若根据前xxx个关系即发现存在矛盾(如A<B,B<C,C<AA<B,B<C,C<AA<B,B<C,C<A),输出
InconsistencyInconsistencyInconsistency foundfoundfound afterafterafter 222 relations.relations.relations.
若根据这m个关系无法确定这n个元素的顺序,输出
SortedSortedSorted sequencesequencesequence cannotcannotcannot bebebe determined.determined.determined.
(提示:确定nnn个元素的顺序后即可结束程序,可以不用考虑确定顺序之后出现矛盾的情况)
输入输出样例
输入 #1
4 6
A<B
A<C
B<C
C<D
B<D
A<B
输入 #2
3 2
A<B
B<A
输入 #3
26 1
A<Z
输出 #1
SortedSortedSorted sequencesequencesequence determineddetermineddetermined afterafterafter 444 relations:relations:relations: ABCD.ABCD.ABCD.
输出 #2
InconsistencyInconsistencyInconsistency foundfoundfound afterafterafter 222 relations.relations.relations.
输出 #3
SortedSortedSorted sequencesequencesequence cannotcannotcannot bebebe determined.determined.determined.
解题思路
每加入一个关系,就做一次拓扑排序。
结果:
- 确定顺序。
- 出现矛盾(出现环)。
- 确认不了,也没有矛盾。
解决:
- 这个挺好做的,以一个数组f[]f[]记录最长链,如果拓扑排序后,所有点都搜过&&最长链==字母数,那么顺序一定确认。
- 这个更好做了,如果做完拓扑后,有些点的入度还是不为0,那就一定有矛盾。
- 这个最好做了 (滑稽) ,前两个都不是就是第三个了。
代码
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
char c[3];
int n,m,k,h,t,ans,head[30],ru[30],ru1[30],f[30],q[30];
struct c{
int x,next;
}a[30000];
void add(int x,int y){
++k;
a[k].x=y;
a[k].next=head[x];
head[x]=k;
}
void topu(){
h=t=ans=0;
for(int i=1;i<=n;i++)
{
f[i]=0;
ru[i]=ru1[i];
if(!ru[i])
{
q[++t]=i;
f[i]=1;
}
}
while(h<t)
{
h++;
for(int i=head[q[h]];i;i=a[i].next)
{
ru[a[i].x]--;
f[a[i].x]=max(f[a[i].x],f[q[h]]+1);//累计链长
ans=max(ans,f[a[i].x]);//求最长链
if(!ru[a[i].x])
q[++t]=a[i].x;
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%s",&c);
int x=c[0]-'A'+1,y=c[2]-'A'+1;
if(x==y)
{
printf("Inconsistency found after %d relations.",i);
return 0;
}
add(x,y);
ru1[y]++;
topu();
for(int j=1;j<=n;j++)
if(ru[j]){//拓扑后入度不为0
printf("Inconsistency found after %d relations.",i);
return 0;
}
if(ans==n)//最长链已经包括了所有的字母
{
printf("Sorted sequence determined after %d relations: ",i);
for(int j=1;j<=t;j++)
printf("%c",q[j]+'A'-1);
printf(".");
printf("\n");
return 0;
}
}
printf("Sorted sequence cannot be determined.");
}