题目描述
一个不同的值的升序排序数列指的是一个从左到右元素依次增大的序列,例如,一个有序的数列
A
,
B
,
C
,
D
A,B,C,D
A,B,C,D 表示
A
<
B
,
B
<
C
,
C
<
D
A<B,B<C,C<D
A<B,B<C,C<D。在这道题中,我们将给你一系列形如A<B的关系,并要求你判断是否能够根据这些关系确定这个数列的顺序。
输入格式
第一行有两个整数
n
,
m
,
n
n,m,n
n,m,n表示需要排序的元素数量,
2
<
=
n
<
=
26
2<=n<=26
2<=n<=26,第
1
1
1到
n
n
n个元素将用大写的
A
,
B
,
C
,
D
…
A,B,C,D…
A,B,C,D…表示。m表示将给出的形如A<B的关系的数量。
接下来有 m m m行,每行有 3 3 3个字符,分别为一个大写字母,一个<符号,一个大写字母,表示两个元素之间的关系。
输出格式
若根据前
x
x
x个关系即可确定这n个元素的顺序
y
y
y
…
y
yyy…y
yyy…y(如
A
B
C
ABC
ABC),输出
S
o
r
t
e
d
Sorted
Sorted
s
e
q
u
e
n
c
e
sequence
sequence
d
e
t
e
r
m
i
n
e
d
determined
determined
a
f
t
e
r
after
after
x
x
x
xxx
xxx
r
e
l
a
t
i
o
n
s
:
relations:
relations:
y
y
y
…
y
.
yyy…y.
yyy…y.
若根据前
x
x
x个关系即发现存在矛盾(如
A
<
B
,
B
<
C
,
C
<
A
A<B,B<C,C<A
A<B,B<C,C<A),输出
I
n
c
o
n
s
i
s
t
e
n
c
y
Inconsistency
Inconsistency
f
o
u
n
d
found
found
a
f
t
e
r
after
after
2
2
2
r
e
l
a
t
i
o
n
s
.
relations.
relations.
若根据这m个关系无法确定这n个元素的顺序,输出
S
o
r
t
e
d
Sorted
Sorted
s
e
q
u
e
n
c
e
sequence
sequence
c
a
n
n
o
t
cannot
cannot
b
e
be
be
d
e
t
e
r
m
i
n
e
d
.
determined.
determined.
(提示:确定 n n n个元素的顺序后即可结束程序,可以不用考虑确定顺序之后出现矛盾的情况)
输入输出样例
输入 #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
S
o
r
t
e
d
Sorted
Sorted
s
e
q
u
e
n
c
e
sequence
sequence
d
e
t
e
r
m
i
n
e
d
determined
determined
a
f
t
e
r
after
after
4
4
4
r
e
l
a
t
i
o
n
s
:
relations:
relations:
A
B
C
D
.
ABCD.
ABCD.
输出 #2
I
n
c
o
n
s
i
s
t
e
n
c
y
Inconsistency
Inconsistency
f
o
u
n
d
found
found
a
f
t
e
r
after
after
2
2
2
r
e
l
a
t
i
o
n
s
.
relations.
relations.
输出 #3
S
o
r
t
e
d
Sorted
Sorted
s
e
q
u
e
n
c
e
sequence
sequence
c
a
n
n
o
t
cannot
cannot
b
e
be
be
d
e
t
e
r
m
i
n
e
d
.
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.");
}