J: Derangement

本文探讨了如何通过最少次数的相邻元素交换操作使给定的排列满足错位排列条件,即每个元素都不在其原始位置上。介绍了算法实现的具体步骤,并提供了一段C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题 J: Derangement
时间限制: 1 Sec 内存限制: 128 MB
提交: 416 解决: 213
[提交] [状态] [讨论版] [命题人: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.
大体思路:交换分为两种情况:一种是相邻的两个都需要交换,另外一种是相邻两个中只需要交换一个。注意在最后位置上的一个元素需要特殊考虑!

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
    int n; cin>>n;
    int a[100005],p[100005];
    memset(p,1,sizeof(p));
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        if(a[i]==i)
            p[i]=0;
    }
    int cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(i!=n)
        {
            if(p[i]==0&&p[i+1]==0)
            {
                cnt++;
                p[i]=1;
                p[i+1]=1;
            }
            else if(p[i]==0&&p[i+1]!=0)
            {
                cnt++;
                p[i]=1;
            }
        }
        else
        {
            if(p[i]==0)
            {
                cnt++;
                p[i]=1;
            }
        }
    }
    cout<<cnt<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值