首页 > 其他 > 详细

AtCoder Beginner Contest 048 C Boxes and Candies

时间:2021-04-03 20:13:38      阅读:16      评论:0      收藏:0      [点我收藏+]

Problem Statement

There are N

boxes arranged in a row. Initially, the i-th box from the left contains ai

candies.

Snuke can perform the following operation any number of times:

  • Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

  • Any two neighboring boxes contain at most x
  • candies in total.

Find the minimum number of operations required to achieve the objective.

Constraints

  • 2N105
  • 0ai109
  • 0x109
 

Input

The input is given from Standard Input in the following format:

N x 

a1 a2 ... aN
 

Output

Print the minimum number of operations required to achieve the objective.

 

从前往后遍历盒子,当遍历至第i个盒子时,设法让对任意0<j<i,有a[j]+a[j+1]<=x,则只要考虑a[i]+a[i+1]是否小于等于x。若不满足,则优先从a[i+1]里拿(已知a[i-1]+a[i]<=x,但a[i+1]+a[i+2]有可能大于x),这样能保证操作数最少。

代码如下:

#include <iostream>
#include <cstdio>
#define maxn 100010
#define ll long long
using namespace std;
int a[maxn];
int n,x;
ll ans;
int main()
{
    scanf("%d%d", &n, &x);
    for (int i = 1; i <= n; i++)
        scanf("%d", a + i);
    for (int i = 1; i < n; i++)
    {
        while (a[i] + a[i + 1] > x)
        {
            if (a[i + 1])
            {
                if (a[i] >= x )//只从a[i+1]拿不满足要求
                {
                    ans += a[i + 1];
                    a[i + 1] = 0;//不要傻乎乎地每次-1,否则会TLE
                }
                else
                {
                    ans += a[i] + a[i + 1] - x;
                    a[i + 1] = x - a[i];
                }
            }
            else//a[i+1]==0
            {
                ans += a[i] - x;
                a[i] = x;
            }
        }
    }
    printf("%lld", ans);
    return 0;
}

 

AtCoder Beginner Contest 048 C Boxes and Candies

原文:https://www.cnblogs.com/yangyi2120/p/14614535.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!