codeforces 855 B. Marvolo Gaunt's Ring (前缀最大,dp)

题目链接

题意:给出n,p,q,r,以及n(1E5)个数,所有数的范围都是[-1E9,1E9],现在问p_a[i]+q_a[j]+r*a[k]的最大值,满足1<=i<=j<=k<=n

思路:傻逼dp...

我。。好菜啊。。。万年dp苦手。

直接转载官方题解了。。。思路的重点是维护了一个最大前缀值。

_dp_[_i_][0] stores maximum of value _p_·_a__x_ for _x_ between 1 and _i_. Similarly _dp_[_i_][1] stores the maximum value of _p_·_a__x_ + _q_·_a__y_ such that _x_ ≤ _y_ ≤ _i_ and _dp_[_i_][2] stores maximum value of _p_·_a__x_ + _q_·_a__y_ + _r_·_a__z_ for _x_ ≤ _y_ ≤ _z_ ≤ _i_.

To calculate the dp:

dp[i][0] = max(dp[i - 1][0], p·a__i)

dp[i][1] = max(dp[i - 1][1], dp[i][0] + q·a__i)

dp[i][2] = max(dp[i - 1][2], dp[i][1] + r·a__i)

The answer will be stored in dp[n][2]

/* ***********************************************
Author :111qqz
Created Time :2017年09月25日 星期一 19时26分34秒
File Name :B.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <set>
 8#include <map>
 9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define PB push_back
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
 1using namespace std;
 2const double eps = 1E-8;
 3const int dx4[4]={1,0,0,-1};
 4const int dy4[4]={0,-1,1,0};
 5const int inf = 0x3f3f3f3f;
 6const int N=1E5+7;
 7LL a[N];
 8LL p,q,r;
 9int n;
10LL dp[N][3];
11int main()
12{
13#ifndef  ONLINE_JUDGE 
14    freopen("./in.txt","r",stdin);
15#endif
16    cin>>n>>p>>q>>r;
17    for ( int i = 1 ; i <= n ; i++) cin>>a[i];
18    LL ans = 1LL<<60;
19    ans*=-5LL;
20    ms(dp,0xc0);
21    //重要的是维护一个前缀最大值。
22    for ( int i = 1 ; i <= n ; i++)
23    dp[i][0] = max(dp[i-1][0],p*a[i]);
24    for ( int i = 1 ; i <= n ; i++)
25    dp[i][1] = max(dp[i-1][1],dp[i][0]+q*a[i]);
26    for ( int i = 1 ; i <= n ; i++)
27    dp[i][2] = max(dp[i-1][2],dp[i][1]+r*a[i]);
28    cout<<dp[n][2]<<endl;
1#ifndef ONLINE_JUDGE  
2    fclose(stdin);
3#endif
4    return 0;
5}