#abc311c. C - Find it!(WAITING SPJ)

C - Find it!(WAITING SPJ)

Score : 350350 points

问题描述

存在一个有向图,包含 NN 个顶点和 NN 条边。 第 ii 条边从顶点 ii 指向顶点 AiA_i。(约束条件保证了 iAii \neq A_i。) 寻找一个不含重复顶点的有向循环。 在本问题的约束条件下可以证明存在解。

注释

顶点序列 B=(B1,B2,,BM)B = (B_1, B_2, \dots, B_M) 被称为有向循环,当满足以下所有条件时:

  • M2M \geq 2
  • 存在从顶点 BiB_i 到顶点 Bi+1B_{i+1} 的边。 (1iM1)(1 \leq i \leq M-1)
  • 存在从顶点 BMB_M 到顶点 B1B_1 的边。
  • iji \neq j,则 BiBjB_i \neq B_j

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

There is a directed graph with NN vertices and NN edges. The ii-th edge goes from vertex ii to vertex AiA_i. (The constraints guarantee that iAii \neq A_i.) Find a directed cycle without the same vertex appearing multiple times. It can be shown that a solution exists under the constraints of this problem.

Notes

The sequence of vertices B=(B1,B2,,BM)B = (B_1, B_2, \dots, B_M) is called a directed cycle when all of the following conditions are satisfied:

  • M2M \geq 2
  • The edge from vertex BiB_i to vertex Bi+1B_{i+1} exists. (1iM1)(1 \leq i \leq M-1)
  • The edge from vertex BMB_M to vertex B1B_1 exists.
  • If iji \neq j, then BiBjB_i \neq B_j.

Constraints

  • All input values are integers.
  • 2N2×1052 \le N \le 2 \times 10^5
  • 1AiN1 \le A_i \le N
  • AiiA_i \neq i

Input

The input is given from Standard Input in the following format:

NN

A1A_1 A2A_2 \dots ANA_N

Output

Print a solution in the following format:

MM

B1B_1 B2B_2 \dots BMB_M

MM is the number of vertices, and BiB_i is the ii-th vertex in the directed cycle.

The following conditions must be satisfied:

  • 2M2 \le M
  • Bi+1=ABiB_{i+1} = A_{B_i} ( 1iM11 \le i \le M-1 )
  • B1=ABMB_{1} = A_{B_M}
  • BiBjB_i \neq B_j ( iji \neq j )

If multiple solutions exist, any of them will be accepted.

Sample Input 1

7
6 7 2 1 3 4 5

Sample Output 1

4
7 5 3 2

$7 \rightarrow 5 \rightarrow 3 \rightarrow 2 \rightarrow 7$ is indeed a directed cycle.

Here is the graph corresponding to this input:

Here are other acceptable outputs:

4
2 7 5 3
3
4 1 6

Note that the graph may not be connected.

Sample Input 2

2
2 1

Sample Output 2

2
1 2

This case contains both of the edges 121 \rightarrow 2 and 212 \rightarrow 1. In this case, 1211 \rightarrow 2 \rightarrow 1 is indeed a directed cycle.

Here is the graph corresponding to this input, where 121 \leftrightarrow 2 represents the existence of both 121 \rightarrow 2 and 212 \rightarrow 1:

Sample Input 3

8
3 7 4 7 3 3 8 2

Sample Output 3

3
2 7 8

Here is the graph corresponding to this input:

update @ 2024/3/10 08:50:26