原文
Arthur owns a ski resort on a mountain. There are landing spots on the mountain numbered from to from the top to the foot of the mountain. The spots are connected with one-directional ski tracks. All tracks go towards the foot of the mountain, so there are no directed cycles formed by the tracks. There are at most two tracks leaving each spot, but many tracks may enter the same spot.
A skier can start skiing from one spot and stop in another spot if there is a sequence of tracks that lead from the starting spot and end in the ending spot. Unfortunately, recently there were many accidents, because the structure of the resort allows a skier to go through dangerous paths, by reaching high speed and endangering himself and the other customers. Here, a path is called dangerous, if it consists of at least two tracks.
Arthur wants to secure his customers by closing some of the spots in a way that there are no dangerous paths in the resort. When a spot is closed, all tracks entering and leaving that spot become unusable.
Formally, after closing some of the spots, there should not be a path that consists of two or more tracks.
Arthur doesn’t want to close too many spots. He will be happy to find any way to close at most spots so that the remaining part is safe. Help him find any suitable way to do so.
Input
The first line contains a single positive integer — the number of test cases. test case description follows.
The first line of each description contains two integers and () — the number of landing spots and tracks respectively.
The following lines describe the tracks. Each of these lines contains two integers and () — indices of the starting and finishing spots for the respective track. It is guaranteed that at most two tracks start at each spot. There may be tracks in which starting and finishing spots both coincide.
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, print a single integer () — the number of spots to be closed. In the next line, print distinct integers — indices of all spots to be closed, in any order.
If there are several answers, you may output any of them. Note that you don’t have to minimize . It can be shown that a suitable answer always exists.
Example
input
1 | 2 |
output
1 | 2 |
Note
In the first sample case, closing any two spots is suitable.
In the second sample case, closing only the spot is also suitable.
大致意思
给出一个有向无环图,所有定点的出度不超过2,入度不做限制,同时限定边的起始点一定比终止点要小(是从山顶到山脚的滑雪道)。
要求去掉其中的一些顶点(不多于),使得图中没有长度超过2的路径。
思路
贪心想法为从节点1(山顶)向后分层级来遍历,如果是第一条连边则保留,第二条则删除相关联节点。
如之后代码中所表示的level,这里通过level将所有顶点分成三类,下标为节点对应的level,形式化表述如下:
- 包含只拥有来自入边的顶点
- 包含至少有一条来自入边,但是没有来自入边的顶点
- 包含至少有一条来自入边的顶点
对应的就是删除所有中的顶点,下面来证明为什么可以保证不超过:
由于至少有一条来自的边,而一个顶点最多两条出边,所以最多有条出边,那么有着,同理有着。于是,所以。
只需要从山顶到山脚扫描一遍就可以确定哪些是当中的顶点,这里的时间复杂度为。
注意:如果对整个level数组进行memset操作,有一个的case会超时!
代码
1 |
|