1270 数组的最大代价 dp

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1270&judgeId=194704

一开始贪心,以为就两种情况,大、小、大、小.....这样下去

小、大、小、大、....这样下去,

结果翻车。比如1、2、1、1、2、1这个样例

就不行了。

那么以dp[i][0]表示前i个数,第i个数选了小的数字,能产生的最大差值,

dp[i][1]同理,转移的时候,上一唯也是两种情况,所以一共4中情况。

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <assert.h>
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;


#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <bitset>
int dp[2][2];
void work() {
    int n;
    scanf("%d", &n);
    int x;
    scanf("%d", &x);
    int pre = x;
    int now = 0;
    for (int i = 2; i <= n; ++i) {
        scanf("%d", &x);
        now = !now;
        dp[now][0] = dp[!now][1] + abs(1 - pre);
        dp[now][0] = max(dp[now][0], dp[!now][0] + 1 - 1);

        dp[now][1] = dp[!now][1] + abs(x - pre);
        dp[now][1] = max(dp[now][1], dp[!now][0] + x - 1);
        pre = x;
    }
    cout << max(dp[now][0], dp[now][1]) << endl;
}

int main() {
#ifdef local
    freopen("data.txt", "r", stdin);
//    freopen("data.txt", "w", stdout);
#endif
    work();
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/liuweimingcprogram/p/6361947.html