题解 P1969 【积木大赛】

· · 题解

贪心经典题

这道题有一个重点:

不知道怎样增加(因为0的原因)

我们先解决第一问。 按贪心的思路,一次性增加越多越好。

可是,有了0就不能增加了啊!

所以,我们有了一个绝妙的方案:

求差!

为什么这种方案行得通呢?

我们想,如果一个值比前面的要小,做前面的时候就一下解决了。于是我们有了一个O(n)的node:

//p1696 积木大赛 
#include<bits/stdc++.h>
using namespace std;
int read() {//快读 
    int x=0,f=1;
    char ch=getchar();
    while (ch<'0' || ch>'9') {
        if (ch=='-')f=-1;//读入负数(虽然这题没有) 
        ch=getchar();
    }
    while ('0'<=ch && ch<='9') {
        x=(x<<3)+(x<<1)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
int main() {
    int n=read();
    int i;
    int ans=read();//ans读入第一个值。 
    int a,b=ans;//a用来输入,b用来比较。 
    for(i=2; i<=n; i++) {
        a=read();
        if(a>b) {//如果b比a大,a在输入前就已经做完了。 
            ans+=a-b;//现在还差的是a比b多的部分 
        }
        b=a;//迭代更新 
    }
    cout<<ans;
    return 0;//可有可无,不过比赛建议用上哦qwq 
}