Contest1391 - 2018年第三阶段个人训练赛第六场.Derangement(思维)

问题 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;
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值