[Codeforces 484D Kindergarten] DP
知识点:dynamic programming
greedy
1. 题目链接
[Codeforces 484D Kindergarten]
2. 题意描述
给定一个包含
n
个元素的数组,我们可以把位置连续的数分为一组,每组至少包含一个元素。
每组对答案的贡献是这个组内最大的数和最小的数的差值。
对于单个元素组成的组,差值为0。输出答案的最大值
3. 解题思路
显然,每一组都是单调的。并且拐点是一个组的首元素或者尾元素。这是很关键的一步。
然后呢,设dp[i]表示前
i
个数最大的答案,pre表示左边最近的一个拐点。那么有
4. 实现代码
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int INF = 0x3f3f3f3f;
const LL INFL = 0x3f3f3f3f3f3f3f3fLL;
const LB eps = 1e-8;
const int MAXN = 1e6 + 5;
const int MOD = 1e9 + 7;
int n;
LL a[MAXN], dp[MAXN], ans;
template<typename T> T umax(T& a, T b) { a = max(a, b); }
bool check(int x) {
if(a[x - 1] >= a[x] && a[x] <= a[x + 1]) return true;
if(a[x - 1] <= a[x] && a[x] >= a[x + 1]) return true;
return false;
}
int main() {
#ifdef ___LOCAL_WONZY___
freopen("input.txt", "r", stdin);
#endif // ___LOCAL_WONZY___
while(~scanf("%d", &n)) {
for(int i = 1; i <= n; ++i) scanf("%I64d", &a[i]);
dp[1] = 0;
int pre = 1;
for(int i = 2; i <= n; ++i) {
dp[i] = max(abs(a[i] - a[pre]) + dp[pre - 1], abs(a[i] - a[pre + 1]) + dp[pre]);
if(check(i)) pre = i;
}
printf("%I64d\n", dp[n]);
}
return 0;
}