POJ 1094 拓扑排序

Sorting It All Out
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 27010 Accepted: 9336

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

Sample Output

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

Source

 

拓扑排序的一个水题,虽说是水题,但是写起来要保证逻辑清晰倒是挺难,曾经写过两遍这个题,但是第二遍时还是调试了半天。

分析其原因,一个是代码能力还不强,总是有很多手误,再一个是做题时盲目追求速度,导致逻辑不够清晰。

思路(可能很啰嗦,是为了理清我的逻辑):

首先,题目要求如果能在前几个输入结束后就确定结果(即发现矛盾或者得到正确唯一的顺序),就不在进行后面的处理(只要读入即可),所以必须要每读入一次数据就要处理一次。

其次,进行操作的过程中,可能需要对每个元素的入度进行处理,所以就需要有一个拷贝数组储存入度值,保证下一次读入数据时入度值没有因为操作而改变。

再次,需要一个标记数组记录每个元素是否被访问,如果被访问,获取下一个入度为0的节点时就不能考虑这个节点。

如果处理过程中发现环,就可以做出标记,后面就只读入数据不进行处理,同时应该记录当前一共读入了几个数据,以便输出。

同样,如果处理过程中发现每次去入度为0的点的这个操作都只有唯一的取法,并成功处理n个点退出,做出标记,记录当前读入了几个数据,同时还要记录方案。

大概就是这么多,希望能吸取教训,做题时不贪快,保证逻辑的清晰。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值