P1347 排序

题目描述

一个不同的值的升序排序数列指的是一个从左到右元素依次增大的序列,例如,一个有序的数列 A,B,C,D 表示A<B,B<C,C<D。在这道题中,我们将给你一系列形如 A<BA<B 的关系,并要求你判断是否能够根据这些关系确定这个数列的顺序。

输入格式

第一行有两个正整数 n,m 表示需要排序的元素数量,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 x relations.

若根据这 m 个关系无法确定这 n 个元素的顺序,输出

Sorted sequence cannot be determined.

(提示:确定 n 个元素的顺序后即可结束程序,可以不用考虑确定顺序之后出现矛盾的情况)

思路

显然,对于每一次输入,我们都需要一次topsort,如果其中有环,则为2情况,可以退出;如果无环且topsort唯一,输出1情况并退出;最后,如果所有都读入完还没有退出,则为3情况。
code:

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,m,head[27],tot=1,rw[27];
char x,z,y;
bool o[27][27];
struct f{
	int to,next;
} a[601];
void add(int x,int y)
{
	a[tot].to=y;
	a[tot].next=head[x];
	head[x]=tot++;
	return;
}
queue<int> wj;
string po;
bool topsort(int u)
{
	int rd[27];
	memcpy(rd,rw,sizeof(rw));
	po="";
	int s=0,syg=0;
	bool bb=0;
	for (int i=1;i<=n;i++)
	{
		if (!rd[i])
		{
			y=i+'A'-1;
			s++;
			po+=y;
			wj.push(i);
		}
	}
	if (s-syg>1) bb=1;
	syg=s;
	while (wj.size())
	{
		int x=wj.front();
		wj.pop();
		for (int i=head[x];i;i=a[i].next)
		{
			rd[a[i].to]--;
			if (!rd[a[i].to])
			{
				s++;
				y=a[i].to+'A'-1;
				po+=y;
				wj.push(a[i].to);
			}
		}
		if (s-syg>1) bb=1;
		syg=s;
	}
	if (s!=n)
	{
		cout<<"Inconsistency found after "<<u<<" relations.";
		return 1;
	}
	if (s==n&&bb==0)
	{
		cout<<"Sorted sequence determined after "<<u<<" relations: "<<po<<".";
		return 1;
	}
	return 0;
}
int main()
{
	cin>>n>>m;
	for (int i=1;i<=m;i++)
	{
		cin>>x>>z>>y;
		x-='A';
		x++;
		y-='A';
		y++;
		if (o[x][y]==0)
		{
			add(x,y);
			rw[y]++;
			o[x][y]=1;
		}
		if (topsort(i)) return 0;
	}
	cout<<"Sorted sequence cannot be determined.";
	return 0;
}//cout万岁!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值