1. 程式人生 > >[牛客小白月賽4 H] 相鄰的糖果

[牛客小白月賽4 H] 相鄰的糖果

感覺 CA long ret inpu -m 執行 情況 scrip

Description

有n個盒子擺成一排,每個盒子內都有ai個糖果。
現在你可以執行以下操作:
·你可以選擇任意一個盒子,在選擇的盒子內吃掉一個糖果。
對你的要求如下:
·任何m個相鄰的盒子內糖果數量不能超過x個。
請問,實現要求的最少操作次數是多少?

Input

第一行三個數字n, m, x \((2 ≤ n,m ≤ 10^6,1 ≤ x ≤ 10^9)\)。第二行n個數字\((1 ≤ ai ≤ 10^9)\)

Output

輸出一個操作數,代表實現要求的最少操作數。

Solution

感覺有點像滑動窗口。

從左往右掃過,維護當前區間的和。

如果大於 \(x\),那麽令 \(val[i]-=(tot-x),tot=x\)

註意左邊界即

if(i>m)
    tot-=val[i]

這樣可以解決 \(val[i]\) “不夠” 的情況。

Code

#include<cstdio>
#define N 1000005
#define int long long

int n,m,x;
int val[N],ans;

signed main(){
    scanf("%lld%lld%lld",&n,&m,&x);
    int tot=0;
    for(int i=1;i<=n;i++){
        scanf("%lld"
,&val[i]); tot+=val[i]; if(i>m) tot-=val[i-m]; if(tot>x) val[i]-=tot-x,ans+=tot-x,tot=x; } printf("%lld\n",ans); return 0; }

[牛客小白月賽4 H] 相鄰的糖果