水题讲解:积木大赛

题目描述

春春幼儿园举办了一年一度的“积木大赛”。今年比赛的内容是搭建一座宽度为n的大厦,大厦可以看成由n块宽度为1的积木组成,第i块积木的最终高度需要是hi。

在搭建开始之前,没有任何积木(可以看成n块高度为 0 的积木)。接下来每次操作,小朋友们可以选择一段连续区间[l, r],然后将第第 L 块到第 R 块之间(含第 L 块和第 R 块)所有积木的高度分别增加1。

小 M 是个聪明的小朋友,她很快想出了建造大厦的最佳策略,使得建造所需的操作次数最少。但她不是一个勤于动手的孩子,所以想请你帮忙实现这个策略,并求出最少的操作次数。

输入输出格式

输入格式:

输入文件为 block.in

输入包含两行,第一行包含一个整数n,表示大厦的宽度。

第二行包含n个整数,第i个整数为hi 。

输出格式:

输出文件为 block.out

仅一行,即建造所需的最少操作数。

输入输出样例

输入样例#1:
5
2 3 4 1 2
输出样例#1:
5

说明

【样例解释】

其中一种可行的最佳方案,依次选择

[1,5] [1,3] [2,3] [3,3] [5,5]

【数据范围】

对于 30%的数据,有1 ≤ n ≤ 10;

对于 70%的数据,有1 ≤ n ≤ 1000;

对于 100%的数据,有1 ≤ n ≤ 100000,0 ≤ hi≤ 10000。

#include<cstdio>
using namespace std;
#define ct    register int 
#define cr   register char
#define fr(a,b,c)  for(ct a=b;a<=c;a++)
#define g()     getchar()
int in(){ct f=1,x=0;cr c=g();for(;c<'0'||c>'9';c=g())if(c=='-')f=-1;
    for(;'0'<=c&&c<='9';c=g())x=(x<<3)+(x<<1)+(c^48);return x*f;}//read optimization
int main(){
    int n=in(),w,p=0,ans=0;
    fr(i,1,n)w=in(),ans+=(w>p)?w-p:0,p=w;
    //our thinking is to use a greedy algorithm
    //the question ask we to make section_increase to reach the requirement
    //but we had better change our thinking:change build into remove
    //just cut the array into several increasing_section
    //for example:2 3 4 1 2
    //let we cut them :2 3 4 |1 2
    //it's easy to prove we must remove(build) the first variable
    //and after this ,we find that we can change the array into 0 1 2|0 1 now_ans:2
    //just repeat this action and then we can out the ans
    //(just means we have remove all the blocks in the minest steps)
    //why we should plus w-p,because the section_operation can't satisfy it's requirement
    //we should do extra_remove to satisfy it
    //why we should not renew the ans when w>p,
    //because we it's easy to prove that it can be remove in the previous operation
    printf("%d",ans);
}
原文地址:https://www.cnblogs.com/muzu/p/7617797.html