[Codeforces 484D Kindergarten] DP

[Codeforces 484D Kindergarten] DP

知识点:dynamic programming greedy

1. 题目链接

[Codeforces 484D Kindergarten]

2. 题意描述

给定一个包含 n 个元素的数组,我们可以把位置连续的数分为一组,每组至少包含一个元素。(1n1000000)
每组对答案的贡献是这个组内最大的数和最小的数的差值。
对于单个元素组成的组,差值为0。输出答案的最大值

3. 解题思路

显然,每一组都是单调的。并且拐点是一个组的首元素或者尾元素。这是很关键的一步。
然后呢,设dp[i]表示前 i 个数最大的答案,pre表示左边最近的一个拐点。那么有

dp[i]=max(abs(a[i]a[pre])+dp[pre1],abs(a[i]a[pre+1])+dp[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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值