【SSL】1129字母排序
Time Limit:1000MS
Memory Limit:65536K
Description
输入一连串的字母间的小于关系 输出最后的排序
比如输入: A
Input
两个整数 n m (2<=n<=26) (当n=m=0时结束)
m 行"小于关系" (只有小于<)
Output
如果最后的排序存在,输出: Sorted sequence determined after xxx relations: yyy…y.
如果无法完成排序 输出: Sorted sequence cannot be determined.
如果在第x个关系后出现矛盾(如A<B,B<C,C<A) 输出: 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
zju
思路
是【洛谷】P1347 排序的多组数据版,每次要置初值。
每输入一次,做一次拓扑排序。
矛盾输出
Inconsistency found after x relations.
排序唯一输出
Sorted sequence determined after xxx relations: yyy…y.
代码
#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;
}