Educational Codeforces Round 108 (Rated for Div. 2) D. Maximum Sum of Products
原创
©著作权归作者所有:来自51CTO博客作者wx636883f8ce969的原创作品,请联系作者获取转载授权,否则将追究法律责任
传送门 You are given two integer arrays a and b of length n.
You can reverse at most one subarray (continuous subsegment) of the array a.
Your task is to reverse such a subarray that the sum ∑i=1nai⋅bi is maximized.
Input
The first line contains one integer n (1≤n≤5000).
The second line contains n integers a1,a2,…,an (1≤ai≤107).
The third line contains n integers b1,b2,…,bn (1≤bi≤107).
Output
Print single integer — maximum possible sum after reversing at most one subarray (continuous subsegment) of a.
思路:
dp(x,y):表示翻转x,y区间所获得的额外价值,则区间dp过程中记录翻转所得到的最大价值,最后再加上原有的价值。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll a[5010];
ll b[5010];
ll dp[5010][5010];
int main()
{
int n;
cin>>n;
ll ans = 0;
ll sum = 0;
for(int i = 1; i <= n; i++)cin>>a[i];
for(int i = 1; i <= n; i++)cin>>b[i];
for(int i = 1; i <= n; i++)sum += a[i]*b[i];
for(int i = n-1; i >= 1; i--)
{
for(int j = i+1; j <= n; j++)
{
dp[i][j] = dp[i+1][j-1] + a[i]*b[j] + a[j]*b[i] - a[i]*b[i] - a[j]*b[j];
ans = max(ans,dp[i][j]);
}
}
printf("%lld\n",ans+sum);
}