Sorting It All Out (拓扑排序)(能否确定字母排序)

An ascending sorted sequence of distinct values is one in which some form of a less-than operator is used to order the elements from smallest to largest. For example, the sorted sequence A, B, C, D implies that A < B, B < C and C < D. in this problem, we will give you a set of relations of the form A < B and ask you to determine whether a sorted order has been specified or not.

Input

Input consists of multiple problem instances. Each instance starts with a line containing two positive integers n and m. the first value indicated the number of objects to sort, where 2 <= n <= 26. The objects to be sorted will be the first n characters of the uppercase alphabet. The second value m indicates the number of relations of the form A < B which will be given in this problem instance. Next will be m lines, each containing one such relation consisting of three characters: an uppercase letter, the character "<" and a second uppercase letter. No letter will be outside the range of the first n letters of the alphabet. Values of n = m = 0 indicate end of input.

Output

For each problem instance, output consists of one line. This line should be one of the following three: 

Sorted sequence determined after xxx relations: yyy...y. 
Sorted sequence cannot be determined. 
Inconsistency found after xxx relations. 

where xxx is the number of relations processed at the time either a sorted sequence is determined or an inconsistency is found, whichever comes first, and yyy...y is the sorted, ascending sequence. 

Sample Input

4 6
A

Sample Output

Sorted sequence determined after 4 relations: ABCD.
Inconsistency found after 2 relations.
Sorted sequence cannot be determined.

题意:对于N个大写字母,给定它们之间的关系,要求判断下列三种情况
         1.到第k次就能确定有环  
         2.到第k次就能确定字母间关系
        3.直到判断完所有输入的字母关系,还是无法确定字母间关系 

 思路:每次输入都要进行拓扑排序来判断上述三种情况

AC代码:

//采用临接表存储字母关系
/*三种情况
 1.到第k次就能确定有环  
 2.到第k次就能确定字母间关系
 3.直到所以字母关系输尽,还是无法确定字母间关系 
 */ 
#include 
#include
#include
#include
#include
using namespace std;
const int N=30;
vector G[N];
int n,m;
int deg[N],vis[N];
int d[N],ans[N];
//拓扑排序模板 
int Tsort()
{
	for(int i=0;i q;
	for(int i=0;i1) flag=1;//如果度为0的字母个数不为1,则是说明n个字母的关系处于不确定状态(如果能确定字母顺序,q.size()==1) 
		int p=q.front();
		q.pop();
		ans[cnt++]=p;//cnt统计度为0的字母个数,用于判断是否有环,如果cnt!=n,则说明有环 
		for(int i=0;i>n>>m)
	{
		if(n==0&&m==0) break;
		for(int i=0;i

 

你可能感兴趣的:(拓扑排序)