题目描述
题目
一个不同的值的升序排序数列指的是一个从左到右元素依次增大的序列,例如,一个有序的数列A,B,C,D 表示A<B,B<C,C<D。在这道题中,我们将给你一系列形如A<B的关系,并要求你判断是否能够根据这些关系确定这个数列的顺序。
输入格式
第一行有两个整数n,m,n表示需要排序的元素数量,2<=n<=26,第1到n个元素将用大写的A,B,C,D…表示。m表示将给出的形如A<B的关系的数量。
接下来有m行,每行有3个字符,分别为一个大写字母,一个<符号,一个大写字母,表示两个元素之间的关系。
输出格式
若根据前x个关系即可确定这n个元素的顺序yyy…y(如ABC),输出
Sorted sequence determined after xxx relations: yyy…y.
若根据前x个关系即发现存在矛盾(如A<B,B<C,C<A),输出
Inconsistency found after 2 relations.
若根据这m个关系无法确定这n个元素的顺序,输出
Sorted sequence cannot be determined.
(提示:确定n个元素的顺序后即可结束程序,可以不用考虑确定顺序之后出现矛盾的情况)
输入输出样例
输入 #1
4 6
A<B
A<C
B<C
C<D
B<D
A<B
输出 #1
Sorted sequence determined after 4 relations: ABCD.
输入 #2
3 2
A<B
B<A
输出 #2
Inconsistency found after 2 relations.
输入 #3
26 1
A<Z
输出 #3
Sorted sequence cannot be determined.
分析:
用拓扑排序 每次输入一个关系就做一次
一共会出现
3
3
3种情况 最后分别判断就可以了
1.
1 .
1.判断矛盾 其实就是是否出现环 根据判断输出情况
2
2
2(题目)
2.
2 .
2.拓扑把度清零 找出最长链 如果最长链小于
n
n
n 则没有关系
反之 则输出情况
1
1
1(题目)
3.
3 .
3.根据这
m
m
m个关系无法确定这
n
n
n个元素的顺序 则为情况
3
3
3(题目)
每次输入要判断
a
a
a与
c
c
c是否重复 会出现矛盾
CODE:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int d[100010],f[100010],h[100010],p[100010],v[100010],ans[10010],len;
int n,m,tot,head,tail;
char x,y,z;
struct node
{
int to,next;
}a[100010];
void add(int x,int y)
{
a[++tot]=(node){y,h[x]}; //邻接表
h[x]=tot;
}
void topsort() //拓扑排序
{
memset(ans,0,sizeof(ans));
memset(v,0,sizeof(v));
head=0,tail=0,len=0;
for(int i=1;i<=n;i++)
d[i]=f[i];
for(int i=1;i<=n;i++)
if(!d[i])
{
p[++tail]=i;
v[i]=1;
ans[i]=1;
}
while(head<tail)
{
head++;
for(int i=h[p[head]];i;i=a[i].next)
{
if(v[a[i].to])
continue;
ans[a[i].to]=max(ans[a[i].to],ans[p[head]]+1);
len=max(len,ans[a[i].to]); //找最长链
d[a[i].to]--;
if(!d[a[i].to])
{
p[++tail]=a[i].to;v[a[i].to]=1;
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
cin>>x>>y>>z; //奇妙的地方 用scanf会WA?
if(x==z) //判断a与c
{
cout<<"Inconsistency found after "<<i<<" relations.";
return 0;
}
add(x-64,z-64); //转换数字
f[z-64]++;
topsort();
if(len==n) //情况1
{
cout<<"Sorted sequence determined after "<<i<<" relations: ";
for(int j=1;j<=n;j++)
cout<<char(p[j]+64);
printf(".");
return 0;
}
for(int j=1;j<=n;j++)
{
if(d[j]!=0) //情况2
{
cout<<"Inconsistency found after "<<i<<" relations.";
return 0;
}
}
}
printf("Sorted sequence cannot be determined."); //都不是情况3
return 0;
}