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

#DSU0000059. Đơn giản hóa hoán vị (Sakurako, Kosuke, and the Permutation)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Đơn giản hóa hoán vị (Sakurako, Kosuke, and the Permutation)

Sakurako, Kosuke, and the Permutation

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation pp of 1,2,…,n1,2,\ldots,n. A permutation is called simple if, for every index ii, at least one of pi=ip_i=i and ppi=ip_{p_i}=i holds. Thus, an element either stays in its original position or belongs to a pair of positions whose values point to each other.

In one operation, choose any two positions and swap their current values. The positions need not be adjacent, and each swap counts as one operation. Every intermediate array remains a permutation.

Find the minimum number of swaps needed to obtain a simple permutation.

Input

The first line contains nn; the next line contains p1,…,pnp_1,\ldots,p_n.

Output

Print the minimum number of swaps.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le20; pp is a permutation of 1,2,…,n1,2,\ldots,n.
  • Subtask 2 (30 points): 1≤n≤42001\le n\le4200; pp is a permutation of 1,2,…,n1,2,\ldots,n.
  • Subtask 3 (50 points): 1≤n≤1061\le n\le10^6; pp is a permutation of 1,2,…,n1,2,\ldots,n.

Examples

Input

5
2 3 4 5 1

Output

2

Explanation

The permutation is one cycle of length 5. Making all cycles have length 1 or 2 requires ⌊(5−1)/2⌋=2\lfloor(5-1)/2\rfloor=2 swaps.