D - Derangement 解説 /

実行時間制限: 2 sec / メモリ制限: 256 MB

配点 : 400400

問題文

1,2,..,N1,2,..,N からなる順列 p1,p2,..,pNp_1,p_2,..,p_N が与えられます。 次の操作を何回か (00回でもよい) 行うことが出来ます。

操作: 順列で隣り合う二つの数を選んでスワップする。

何回か操作を行って、任意の 1iN1≤i≤N に対して piip_i ≠ i となるようにしたいです。 必要な操作の最小回数を求めてください。

制約

  • 2N1052≤N≤10^5
  • p1,p2,..,pNp_1,p_2,..,p_N1,2,..,N1,2,..,N の順列である。

入力

入力は以下の形式で標準入力から与えられる。

NN
p1p_1 p2p_2 .. pNp_N

出力

必要な操作の最小回数を出力せよ。


入力例 1Copy

Copy
5
1 4 3 5 2

出力例 1Copy

Copy
2

1144 を入れ替え、その後 1133 を入れ替えることで pp4,3,1,5,24,3,1,5,2 となり、これは条件を満たします。 これが最小回数なので、答えは 22 となります。


入力例 2Copy

Copy
2
1 2

出力例 2Copy

Copy
1

1122 を入れ替えれば条件を満たします。


入力例 3Copy

Copy
2
2 1

出力例 3Copy

Copy
0

初めから条件を満たしています。


入力例 4Copy

Copy
9
1 2 4 9 5 8 7 3 6

出力例 4Copy

Copy
3

Score : 400400 points

Problem Statement

You are given a permutation p1,p2,...,pNp_1,p_2,...,p_N consisting of 11,22,..,NN. You can perform the following operation any number of times (possibly zero):

Operation: Swap two adjacent elements in the permutation.

You want to have piip_i ≠ i for all 1iN1≤i≤N. Find the minimum required number of operations to achieve this.

Constraints

  • 2N1052≤N≤10^5
  • p1,p2,..,pNp_1,p_2,..,p_N is a permutation of 1,2,..,N1,2,..,N.

Input

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

NN
p1p_1 p2p_2 .. pNp_N

Output

Print the minimum required number of operations


Sample Input 1Copy

Copy
5
1 4 3 5 2

Sample Output 1Copy

Copy
2

Swap 11 and 44, then swap 11 and 33. pp is now 4,3,1,5,24,3,1,5,2 and satisfies the condition. This is the minimum possible number, so the answer is 22.


Sample Input 2Copy

Copy
2
1 2

Sample Output 2Copy

Copy
1

Swapping 11 and 22 satisfies the condition.


Sample Input 3Copy

Copy
2
2 1

Sample Output 3Copy

Copy
0

The condition is already satisfied initially.


Sample Input 4Copy

Copy
9
1 2 4 9 5 8 7 3 6

Sample Output 4Copy

Copy
3


2025-03-14 (金)
05:16:37 +00:00