欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Boxes and Candies(水题)

程序员文章站 2023-12-25 22:28:57
...
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
  • 2≤N≤105
  • 0≤ai≤109
  • 0≤x≤109
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.
Sample Input 1

3 3
2 2 2

Sample Output 1

1
Eat one candy in the second box. Then, the number of candies in each box becomes (2,1,2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11
For example, eat six candies in the second box, two in the fourth box, and three in the sixth box. Then, the number of candies in each box becomes (1,0,1,0,0,1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0
The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10
All the candies need to be eaten.

题意:线性表中任意相邻两个数之和不能大于x,若大于x,通过减少的方式来符合要求,每次减少1,问最终一共减少了多少次.

解析:从前往后判断,若两个数之和大于x,即减少了a[i] + a[i-1] - x次,统计到总和sum,循环N次后得到总值输出即可

#include<cstdio>
#include<iostream>

using namespace std;

long long a[100005];

int main()
{
    long long n,x,t;
    while(~scanf("%lld%lld",&n,&x))
    {
        long long sum = 0;
        a[0] = 0;

        for(int i = 1; i <= n; i++)
        {
            scanf("%lld",&a[i]);
            if(a[i] + a[i-1] > x)
            {
                t = a[i] + a[i-1] - x;    //与前一个数值相差的个数
                sum += t;  //统计到总和
                a[i] -= t;   //改变原来的值,以便下一个数判断
            }
        }
        printf("%lld\n",sum);

    }
    return 0;
}

Thank for you like!

相关标签: 简单逻辑

上一篇:

下一篇: