题目描述
公园里有N个花园,初始时每个花园里都没有种花,园丁将花园从1到N编号并计划在编号为i的花园里恰好种A_i朵花,他每天会选择一个区间[L,R](1≤L≤R≤N)并在编号为L到R的花园里各种一朵花,那么园丁至少要花多少天才能完成计划?
输入描述:
第一行包含一个整数N,1≤N≤10^5。
第二行包含N个空格隔开的整数A_1到A_N,0≤A_i≤10^4。
输出描述:
输出完成计划所需的最少天数。
示例1
输入
复制
5
4 1 8 2 5
输出
复制
14
这道题很久以前见过
- 每次选择一段连续的
非零
子数组减去一,求最少操作次数
动态规划 :
- 定义状态 :
dp[i]表示长度为 左端点为 1 右端点为 i 的 子数组最少操作次数
- 转移方程:
-
- 当
a[i]
比前一个a[i-1]
矮,dp[i] = dp[i-1]
,当比前面矮,a[i]
会比前面最大的值a_max
先消除
- 当
-
- 当
a[i]
比前一个高时,dp[i] = dp[i-1] + (a[i]-a[i-1])
,消去前一个a[i-1]
时,a[i]
也一定可以被砍掉高度为a[i-1]
的脚,故前面最大加上当前高出的部分就可以消完
- 当
- 边界条件:
dp[1] = a[1]
,只有一个一定要a[1]
次消除操作
代码
#define debug
#ifdef debug
#include <time.h>
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K, a[MAXN], dp[MAXN];
signed main() {
#ifdef debug
freopen("test.txt", "r", stdin);
clock_t stime = clock();
#endif
read(n);
for(int i=1; i<=n; i++) read(a[i]);
dp[1] = a[1]; //边界
// for(int i=1; i<=n; i++) show(i, a[i]);
for(int i=2; i<=n; i++)
if(a[i] <= a[i-1]) {
dp[i] = dp[i-1];
} else {
dp[i] = dp[i-1] + (a[i] - a[i-1]);
}
// for(int i=1; i<=n; i++) show(dp[i]);
printf("%d\n", dp[n]);
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}