问题 J: Derangement
时间限制: 1 Sec 内存限制: 128 MB
提交: 388 解决: 202
[提交] [状态] [讨论版] [命题人:admin]
题目描述
You are given a permutation p1,p2,…,pN consisting of 1,2,..,N. You can perform the following operation any number of times (possibly zero):
Operation: Swap two adjacent elements in the permutation.
You want to have pi≠i for all 1≤i≤N. Find the minimum required number of operations to achieve this.
Constraints
2≤N≤105
p1,p2,..,pN is a permutation of 1,2,..,N.
输入
The input is given from Standard Input in the following format:
N
p1 p2 .. pN
输出
Print the minimum required number of operations
样例输入
5 1 4 3 5 2
样例输出
2
提示
Swap 1 and 4, then swap 1 and 3. p is now 4,3,1,5,2 and satisfies the condition. This is the minimum possible number, so the answer is 2.
解题思路:如果 N 是偶数,直接统计数字与所在位置相同的数个数,操作是直接和后一个数交换就好。如果 N 是奇数,再判断最后一个需不需要交换。注意:在统计数字与位置相同的数个数时,假如第 k 个数为 k ,那么 ans++ 后,还需要 k++ , 因为第 k 个数字和前一个数字交换后,数字的数值一定不等于所在位置。
参考代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int a[100005];
for(int i=1; i<=n; i++) cin>>a[i];
int f,ans=0;
if(n%2==0)
{
for(int i=1; i<=n; i++)
if(a[i]==i) ans++,i++;
}else{
f=0;
for(int i=1; i<n; i++)
if(a[i]==i){
if(i==n-1) f=1;
ans++,i++;
}
if(!f&&a[n]==n) ans++;
}
cout<<ans<<endl;
}
}