POJ 1094 变量排序 解题报告

题目描述:把不同的变量进行升序排序用小于操作符命令实现的。例如由A < B, B < C 和 C < D 可以得到升序序列A, B, C, D 。

在本题中,你将得到若干条小于操作符命令,形如 A < B 的格式,请你确定利用这些命令,能否得到一个唯一的升序序列。

输入格式:第1行为整数n,m,n(2 <= n <= 26)表示参与排序的是前n个大写字母,m表示给出命令的条数。

输出格式:输出一行:
  如果根据输入能得到唯一的升序序列,则输出“Sorted sequence determined after xxx relations: yyy...y. ”
  如果不能得到唯一的升序序列,则输出“Sorted sequence cannot be determined. ”
  如果不能得到升序序列,则输出“Inconsistency found after xxx relations. ”
  上面的信息中 xxx 是一个整数,是表示至多根据前xxx条信息就可以得出该结论。 yyy...y表示得到的升序序列的大写字母串。

【输入样例】   
   
【样例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】
 Sorted sequence determined after 4 relations: ABCD.


【样例2】
 Inconsistency found after 2 relations.


【样例3】
 Sorted sequence cannot be determined.
 

解题思路:跟据题目描述不难想出该题可以转为图来解决,因为输入均为按照小于操作符命令,所以可以转为有向图,该题翻译过来即判断输入的有向图是否为DAG图(有向无环图)及其拓扑排序是否唯一。主要算法为拓扑排序的BFS算法,只是BFS的返回值应为int,设返回0表示不能得到升序序列,返回1表示能得到唯一的升序序列,返回2表示不能得到唯一的升序序列。对于每读入一条命令都应用BFS判断一下。需注意的是,要确定不能得到唯一的升序序列,需读完所有命令后再判断。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
const int maxn=30;
int N,M,x,y;
char s[maxn];
vector<int>g[maxn],topo;
int rd[maxn],trd[maxn];
struct cmp
{
	bool operator ()(int aa,int bb)
	{
		return aa>bb;
	}
};
int BFS()
{
	priority_queue<int,vector<int>,cmp>q;  //也可以直接用STL队列
	memcpy(trd,rd,sizeof(rd));
	topo.clear();
	for(int i=1;i<=N;i++)
	if(trd[i]==0)  q.push(i);
	int flag=0;
	while(!q.empty())
	{
		if(q.size()>1)  flag=2;
		int i=q.top();  q.pop();
		topo.push_back(i);
		for(int k=0;k<g[i].size();k++)
		{
			int j=g[i][k];
			if(trd[j]>0)  trd[j]--;
			if(trd[j]==0)  q.push(j);
		}
	}
	if(topo.size()<N)  return 0;  //不能得到升序序列
	if(flag==2)  return 2;  //不能得到唯一的升序序列
	return 1;  //能得到唯一的升序序列
}
int main()
{
	freopen("48.in","r",stdin);
	//freopen("48.out","w",stdout);
	scanf("%d%d",&N,&M);
	memset(rd,0,sizeof(rd));
	for(int i=1;i<=M;i++)
	{
		scanf("%s",s);
		x=s[0]-'A'+1;
		y=s[2]-'A'+1;
		g[x].push_back(y);
		rd[y]++;
		int t=BFS();
		if(t==0)
		{
			printf("Inconsistency found after %d relations.\n",i);
			break;  //如果确定不能得到升序序列即可直接输出并退出循环
		}
		if(t==1)
		{
			printf("Sorted sequence determined after %d relations: ",i);
			for(int i=0;i<topo.size();i++)
			printf("%c",topo[i]-1+'A');
			printf(".\n");
			break;  //如果确定能得到唯一的升序序列即可直接输出并退出循环
		}
		if(i==M && t==2)  //需在读完所有命令后判断
		{
			printf("Sorted sequence cannot be determined.\n");
		}
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值