博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
P1347 排序
阅读量:339 次
发布时间:2019-03-04

本文共 1843 字,大约阅读时间需要 6 分钟。

题目描述

一个不同的值的升序排序数列指的是一个从左到右元素依次增大的序列,例如,一个有序的数列 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
#include
#include
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
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 "<
<<" relations."; return 1; } if (s==n&&bb==0) {
cout<<"Sorted sequence determined after "<<<" relations: "<
<<"."; 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万岁!!!

转载地址:http://wuye.baihongyu.com/

你可能感兴趣的文章