POJ 1094 Sorting It All Out 拓扑排序

Sorting It All Out
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 18715   Accepted: 6380

Description

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 
  
A 
  
B 
  
C 
  
B 
  
A 
  
3 2
A 
  
B 
  
26 1
A 
  
0 0

Sample Output

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

 

 题意:根据 给出的 关系式,判断,当出现环时 输出 在第几个关系式 出现环,当可排序时 输出 在第几个关系式可排序,并输出排序顺序。

当所有关系式 输入后 无法排序 则输出无法排序;

思路:因为要输出 第几个关系式,所以 每输入一个关系式 都要对图 进行 拓扑排序,

若发现环 则输出 含有环,若可排序则输出可排序,重点在于 当出现多个0前驱节点时,应将所有0前驱标记, 再对图排序,看看是否含有环; 

输出遵照以下规则:优先级:输出环,输出完整顺序,输出无法排序;

#include 
using namespace std;
bool map[28][28],visit[28];
char ans[28];
int sum[28],temp[28];
int count,n,m;
int top_sort()
{
	int i,j,zero,l,flag=1;
	memcpy(temp, sum, sizeof(temp));
	memset(ans, '\0',sizeof(ans));
	for(i=0; i1)  flag = -1;
		/*无序 但是关系还没输完, 先判断是否有环
		**将 所有0前驱节点 置为-1
		**则 如果不存在 0前驱节点 此图 含有环
		**否则 无环 继续 读取关系式
		*/
		if(zero==0) return 0;//有环
		temp[l]=-1; ans[i]='A'+l;
		for(j=0; j


 

你可能感兴趣的:(POJ)