Description
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt‘s Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of p·ai + q·aj + r·ak for given p, q, r and array a1, a2, ... an such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.
Input
First line of input contains 4 integers n, p, q, r ( - 109 ≤ p, q, r ≤ 109, 1 ≤ n ≤ 105).
Next line of input contains n space separated integers a1, a2, ... an ( - 109 ≤ ai ≤ 109).
Output
Output a single integer the maximum value of p·ai + q·aj + r·ak that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.
Sample Input
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
Hint
In the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
题意:找出最大的ai*p+aj*q+ak*r。保证i<=j<=k
解析:目前我在各个博客中找到了三种解法(其实思想差不多),首先是前后缀数组模拟的:用L[]来记录 i 左边的最大a[]*p值,R[]来记录 i 右边的最大a[]*r最大值,q为中间,最后遍历的时候直接q*a[]来更新最大值就好了:
#include<iostream> #include<cstring> using namespace std; typedef long long ll; const ll inf=0x3f3f3f3f3f3f3f3f; //这注意了,1e18会WA,目前不知道原因 const int maxn = 1e5+10; ll a[maxn],L[maxn],R[maxn]; int main() { ll n,p,q,r; cin>>n>>p>>q>>r; for(int i=1;i<=n;i++) cin>>a[i]; L[1]=a[1]*p; for(int i=2;i<=n;i++) L[i]=max(L[i-1],a[i]*p); R[n]=a[n]*r; for(int i=n-1;i>=1;i--) R[i]=max(R[i+1],a[i]*r); ll sum=-inf; for(int i=1;i<=n;i++) sum=max(sum,L[i]+R[i]+q*a[i]); cout<<sum<<endl; }
第二种:也是模拟,代码最为简单
#include <iostream> using namespace std; typedef long long ll; const ll inf=0x3f3f3f3f3f3f3f3f; int main() { int n,p,q,r; cin>>n>>p>>q>>r; long long x;long long a=-inf,aa=-inf,aaa=-inf; while(n--){ cin>>x; a=max(a,p*x); aa=max(aa,a+q*x); aaa=max(aaa,aa+r*x); } cout<<aaa<<endl; }
第三种:按背包问题来做
#include<iostream> using namespace std; #define INF 0x3f3f3f3f3f3f3f3f typedef long long ll; const int maxn=1e5+10; ll a[maxn],b[4],dp[maxn][4]; int main() { int n; while(cin>>n) { for(int i=1;i<=3;i++) cin>>b[i]; for(int i=1;i<=n;i++) cin>>a[i]; for(int i=0;i<=n;i++) { dp[i][0]=0; for(int j=1;j<=3;j++) dp[i][j]=-INF; } for(int i=1;i<=n;i++) for(int j=1;j<=3;j++) dp[i][j]=max(dp[i][j],max(dp[i-1][j],dp[i][j-1]+(ll)(a[i]*b[j]))); cout<<dp[n][3]<<endl; } return 0; }
Marvolo Gaunt's Ring(巧妙利用前后缀进行模拟)
原文地址:https://www.cnblogs.com/liyexin/p/12339734.html