abc072d <贪心>

D - Derangement

// https://atcoder.jp/contests/abc072/tasks/arc082_b
// <贪心>
// 令0表示p[i]!=i, 1表示p[i]==i,
// 则对于一个需要交换操做的位置, 仅可能有 010 ..11.. 两种情况
// 对于这两种情况, 交换一次即可解决问题, 
// 且存在特点: 不会对周围产生影响, 根据这里特点,
//   可将问题简化为 01 序列, 而与具体是哪个数字无关, 因而遇到1就操作即可
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
using LL = long long;
const int N = 1e5 + 10;
int a[N];

void solv()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; i ++) cin >> a[i];
    int cnt = 0;
    for (int i = 1; i <= n; i ++)
    {
        if (a[i] == i)
        {
            cnt ++;
            if (i < n) swap(a[i], a[i+1]);
            else swap(a[i-1], a[i]);
        }
    }
    cout << cnt << endl;
}

int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int T = 1;
	// cin >> T;
    while (T --)
    {
        solv();
    }
    return 0;
}

posted @ 2023-07-10 17:09  O2iginal  阅读(14)  评论(0)    收藏  举报