Codeforces #380 Subordinates(贪心 构造)

本文介绍了一种使用双指针技巧处理数组元素的操作算法,通过将数组中出现次数为0的元素与非0元素进行交换,实现了特定条件下的最优解。算法过程中运用了计数等数据结构来提高效率。

 从前往后扫,找到一出现次数为0的数,从后面找一个出现不为0的数转化而来。设置两指针l, r来处理。

 

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<vector>
#include<cmath>
#include<utility>
using namespace std;
typedef long long LL;
const int N = 1000008, INF = 0x3F3F3F3F;
int a[N], cnt[N], rem[N];
int main(){
    int n, s;
    cin >> n >> s;
    for(int i = 1; i <= n; i++){
        scanf("%d", &a[i]);
    }
    int ans = 0;
    if(a[s]){
        ans++;
        a[s] = 0;
    }
    for(int i = 1; i <= n; i++){
        cnt[a[i]]++;
    }
    cnt[n] += cnt[0] - 1;
    int l = 1, r = n;
    while(l < r){
        while(cnt[l] && l < r){
            l++;
        }
        while(cnt[r] == 0 && l < r){
            r--;
        }
        if(l < r){
            cnt[l]++;
            cnt[r]--;
            ans++;
        }
    }
    cout<<ans<<endl;



    return 0;
}

  

转载于:https://www.cnblogs.com/IMGavin/p/6104418.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值