BZOJ4996 [Usaco2017 Feb]Why Did the Cow Cross the Road II 排序+前缀和

The long road through Farmer John's farm has NN crosswalks across it, conveniently numbered 1 \ldots N1N (1 \leq N \leq 100,0001N100,000). To allow cows to cross at these crosswalks, FJ installs electric crossing signals, which light up with a green cow icon when it is ok for the cow to cross, and red otherwise. Unfortunately, a large electrical storm has damaged some of his signals. Given a list of the damaged signals, please compute the minimum number of signals that FJ needs to repair in order for there to exist some contiguous block of at least KK working signals.

共有N个信号灯,编号为1~N,有B个信号灯损坏,给你它们的编号。

问,最少修好几个信号灯,可以有K个编号连续的信号灯。

 

思路:这道题比较好的方法是用前缀和f[i]来记录前i个灯有几个是坏的,这样f[i]-f[i-k]就是一组可能的答案,从所有里面找出最小的就是最终的答案。

注意输入不保证递增,所以要先排序

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,k,b;
int a[200000];
int f[200000];
int main()
{
    ios::sync_with_stdio(false);
    int i,j,ans;
    cin >> n >> k >> b;
    for (i=1; i <= b; i++)
        cin >> a[i];
    sort(a+1,a+b+1);
    j=1;
    for (i=1; i <= n; i++)
    {
        if (i==a[j])
        {
            f[i]=f[i-1]+1;
            j++;
        }
        else
            f[i]=f[i-1];
    }
    ans=f[k];
    for (i=k+1; i <= n; i++)
        ans=min(ans,f[i]-f[i-k]);
    cout << ans << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/TMCK/p/7442414.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值