J: Derangement

问题 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
#include
#include
#include
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<return 0;
}

你可能感兴趣的:(数学问题,中石油个人训练)