PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#DSU0000029. Bài toán quỷ nhện – phiên bản khó (Medium Demon Problem (hard version))

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Bài toán quỷ nhện – phiên bản khó (Medium Demon Problem (hard version))

Medium Demon Problem (hard version)

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

There are nn spiders numbered from 11 to nn. Initially, each spider owns exactly one toy. Spider ii has a fixed recipient rir_i, which is different from ii.

Each year, every spider possessing at least one toy simultaneously sends exactly one toy to spider rir_i. A spider with no toys sends nothing. All incoming toys arrive only after every spider has finished sending for that year. A spider may hold multiple toys. The state of the system is the number of toys held by each spider.

Year yy is called stable if the state immediately before the transfers of year yy is identical to the state immediately before year y−1y-1. Year 11 is not stable by definition. Find the first stable year.

Input

The first line contains nn, the second r1,…,rnr_1,\ldots,r_n with 1≤ri≤n1\le r_i\le n and ri≠ir_i\ne i.

Output

Print the index of the first stable year.

Subtasks

  • Subtask 1 (20 points): 2≤n≤402\le n\le40; 1≤ri≤n1\le r_i\le n and ri≠ir_i\ne i.
  • Subtask 2 (30 points): 2≤n≤50002\le n\le5000; 1≤ri≤n1\le r_i\le n and ri≠ir_i\ne i.
  • Subtask 3 (50 points): 2≤n≤2⋅1052\le n\le2\cdot10^5; 1≤ri≤n1\le r_i\le n and ri≠ir_i\ne i.

Examples

Input

5
2 1 4 2 3

Output

5

Explanation

The toy counts just before years 1,2,3,4,51,2,3,4,5 are (1,1,1,1,1)(1,1,1,1,1), (1,2,1,1,0)(1,2,1,1,0), (1,3,0,1,0)(1,3,0,1,0), (1,4,0,0,0)(1,4,0,0,0), and (1,4,0,0,0)(1,4,0,0,0), respectively. Year 55 is the first year whose starting state is identical to that of the preceding year, so the answer is 5.