zoukankan      html  css  js  c++  java
  • Boxes and Candies(贪心)

    Boxes and Candies


    Time limit : 2sec / Memory limit : 256MB

    Score : 300 points

    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

    Copy
    3 3
    2 2 2
    

    Sample Output 1

    Copy
    1
    

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


    Sample Input 2

    Copy
    6 1
    1 6 1 2 0 4
    

    Sample Output 2

    Copy
    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

    Copy
    5 9
    3 1 4 1 5
    

    Sample Output 3

    Copy
    0
    

    The objective is already achieved without performing operations.


    Sample Input 4

    Copy
    2 0
    5 5
    

    Sample Output 4

    Copy
    10
    

    All the candies need to be eaten.

    //一道简单的贪心,我想得太复杂了。。。而且结果要用 long long 保存

     1 #include <stdio.h>
     2  
     3 int box[100005];
     4 int main()
     5 {
     6     int n,x;
     7     while (scanf("%d%d",&n,&x)!=EOF)
     8     {
     9         for (int i=1;i<=n;i++)
    10             scanf("%d",&box[i]);
    11         long long all=0;
    12         if (box[1]>x)
    13         {
    14             all+=box[1]-x;
    15             box[1]=x;
    16         }
    17         for (int i=2;i<=n;i++)
    18         {
    19             int k = box[i]+box[i-1]-x;
    20             if (k>0)
    21             {
    22                 all+=k;
    23                 box[i]-=k;
    24             }
    25         }
    26         printf("%lld
    ",all);
    27     }
    28 }
    View Code
  • 相关阅读:
    【jQuery】用jQuery给文本框添加只读属性【readOnly】
    解决embed标签显示在div上层【转藏】
    width:100% 和 max-width:100%; 有区别吗【转藏】
    一位资深程序员的独白
    jQuery 取值、赋值的基本方法【转藏】
    js判断手机端操作系统(Andorid/IOS)
    PhpStrom 和 wamp 配置 xdebug
    php 中 ?? 和 empty 的 区别
    phpSpreadSheet 中 使用的 一些坑
    html td 限制 高度 和 宽度
  • 原文地址:https://www.cnblogs.com/haoabcd2010/p/6187578.html
Copyright © 2011-2022 走看看