#P17459. [GESP202609 七级] 必经之路

[GESP202609 七级] 必经之路

Problem Description

Given a directed graph GG with nn nodes and mm edges, the nodes in GG are numbered 1,2,…,n1,2,\ldots,n in order. The ii-th edge (1≤i≤m1\le i\le m) goes from node uiu_i to node viv_i.

Any node in GG with in-degree 00 can be a valid starting node, and any node with out-degree 00 can be a valid ending node.

If all possible paths in GG from any valid starting node to any valid ending node must pass through node uu, then uu is called a mandatory node. Note that a mandatory node can be a valid starting node or a valid ending node.

Please find the indices of all mandatory nodes in GG.

For example, in the figure below, the valid starting nodes are node 11 and node 22, and the valid ending nodes are node 77 and node 88.

(1)            (5)---->(7)
   \           ^  \    ^
    v         /    v  /
    (3)      /     (6)
    ^  \    /         \
   /    v  /           v
(2)---->(4)            (8)

All paths from valid starting nodes to valid ending nodes are:

  • 1→3→4→5→71\to 3\to 4\to 5\to 7
  • 1→3→4→5→6→71\to 3\to 4\to 5\to 6\to 7
  • 1→3→4→5→6→81\to 3\to 4\to 5\to 6\to 8
  • 2→3→4→5→72\to 3\to 4\to 5\to 7
  • 2→3→4→5→6→72\to 3\to 4\to 5\to 6\to 7
  • 2→3→4→5→6→82\to 3\to 4\to 5\to 6\to 8
  • 2→4→5→72\to 4\to 5\to 7
  • 2→4→5→6→72\to 4\to 5\to 6\to 7
  • 2→4→5→6→82\to 4\to 5\to 6\to 8

Therefore, there are two mandatory nodes, with indices 4,54,5.

Input Format

The first line contains two positive integers n,mn,m, representing the number of nodes and the number of edges in the directed graph GG.

The next mm lines each contain two positive integers ui,viu_i,v_i, representing a directed edge from node uiu_i to node viv_i.

It is guaranteed that GG has at least one valid starting node and at least one valid ending node, and that there is at least one path from a valid starting node to a valid ending node. Also, there are no isolated nodes (i.e., nodes whose out-degree and in-degree are both 00).

Output Format

The first line contains an integer, representing the number of mandatory nodes kk.

If mandatory nodes exist, then the second line outputs the indices of all mandatory nodes in GG in increasing order.

8 9
1 3
2 3
3 4
4 5
5 6
6 7
6 8
2 4
5 7
2
4 5
8 9
1 3
2 3
3 4
4 5
5 6
6 7
6 8
2 5
4 7
0

Hint

For 40%40\% of the test points, it is guaranteed that 1≤n≤1001\le n\le 100 and 1≤m≤2001\le m\le 200.

For all test points, it is guaranteed that 1≤n≤10001\le n\le 1000 and 1≤m≤20001\le m\le 2000. It is guaranteed that GG has at least one valid starting node and at least one valid ending node, and that there is at least one path from a valid starting node to a valid ending node. Also, there are no isolated nodes (i.e., nodes whose out-degree and in-degree are both 00).

Translated by ChatGPT 5