#abc357e. E - Reachability in Functional Graph

E - Reachability in Functional Graph

Score : 450450 points

问题陈述

有一个有向图,包含 NN 个顶点,编号从 11NN,以及 NN 条边。 每个顶点的出度为 11,从顶点 ii 出发的边指向顶点 aia_i。 计算顶点对 (u,v)(u, v) 的数量,使得从顶点 uu 可以到达顶点 vv

这里,如果存在一个顶点序列 w0,w1,,wKw_0, w_1, \dots, w_K,长度为 K+1K+1,满足以下条件,则顶点 vv 可以从顶点 uu 到达。特别是,如果 u=vu = v,则总是可以到达。

  • w0=uw_0 = u
  • wK=vw_K = v
  • 对于每个 0i<K0 \leq i < K,存在一条从顶点 wiw_i 到顶点 wi+1w_{i+1} 的边。

以上为大语言模型 kimi 翻译,仅供参考。

Problem Statement

There is a directed graph with NN vertices numbered 11 to NN and NN edges.
The out-degree of every vertex is 11, and the edge from vertex ii points to vertex aia_i.
Count the number of pairs of vertices (u,v)(u, v) such that vertex vv is reachable from vertex uu.

Here, vertex vv is reachable from vertex uu if there exists a sequence of vertices w0,w1,,wKw_0, w_1, \dots, w_K of length K+1K+1 that satisfies the following conditions. In particular, if u=vu = v, it is always reachable.

  • w0=uw_0 = u.
  • wK=vw_K = v.
  • For every 0i<K0 \leq i \lt K, there is an edge from vertex wiw_i to vertex wi+1w_{i+1}.

Constraints

  • 1N2×1051 \leq N \leq 2 \times 10^5
  • 1aiN1 \leq a_i \leq N
  • All input values are integers.

Input

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

NN

a1a_1 a2a_2 \dots aNa_N

Output

Print the number of pairs of vertices (u,v)(u, v) such that vertex vv is reachable from vertex uu.

Sample Input 1

4
2 1 1 4

Sample Output 1

8

The vertices reachable from vertex 11 are vertices 1,21, 2.
The vertices reachable from vertex 22 are vertices 1,21, 2.
The vertices reachable from vertex 33 are vertices 1,2,31, 2, 3.
The vertex reachable from vertex 44 is vertex 44.
Therefore, the number of pairs of vertices (u,v)(u, v) such that vertex vv is reachable from vertex uu is 88.
Note that the edge from vertex 44 is a self-loop, that is, it points to vertex 44 itself.

Sample Input 2

5
2 4 3 1 2

Sample Output 2

14

Sample Input 3

10
6 10 4 1 5 9 8 6 5 1

Sample Output 3

41