D. Maximum Sum of Products (DP)

11 篇文章 0 订阅
5 篇文章 0 订阅

D. Maximum Sum of Products

time limit per test 2 seconds
memory limit per test 256 megabytes
input standard input
output standard output

  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.

Examples

input 1

5
2 3 2 1 3
1 3 2 4 2

output 1

29

input 2

2
13 37
2 4

output 2

174

input 3

6
1 8 7 6 3 6
5 9 6 8 8 6

output 3

235

Note

  In the first example, you can reverse the subarray [4,5]. Then a=[2,3,2,3,1] and 2⋅1+3⋅3+2⋅2+3⋅4+1⋅2=29.

  In the second example, you don’t need to use the reverse operation. 13⋅2+37⋅4=174.

  In the third example, you can reverse the subarray [3,5]. Then a=[1,8,3,6,7,6] and 1⋅5+8⋅9+3⋅6+6⋅8+7⋅8+6⋅6=235.

基本思路:

找到交换长度之间的关系,并计算出交换此等长度后的累加和.。

通项公式为:

dp内存储反转子集的累加和

dp[反转子集长度] = a[反转子集头顶点] * b[反转子集尾顶点] + dp[交换子集长度-2] + a[反转子集尾顶点] * b[反转子集头顶点];

反转此子集后的合集累加和 = dp[反转子集长度] + 累加和[反转子集头顶点-1] + 累加和[集合尾节点] - 累加和[反转子集尾顶点]

PS:代码能不看就不要看,写属于是基本思路的微变形,有属于个人习惯的预处理,不怎么好理解。但是如果是完全不会的话就看自己的学习习惯了。

Code

#include<iostream>
#define ll long long
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
int main()
{
    ll n, i, j, sum, t;
    cin >> n;
    ll a[n + 1], b[n + 1], c[n + 2] = {0}, dp[n + 1][n + 1] = {0};

    for ( i = 1; i <= n; i++ ) cin >> a[i];

    for ( i = 1; i <= n; i++ )
    {
        cin >> b[i];
        dp[0][i] = dp[0][i + 1] = dp[0][i + 2] = 0;
        dp[1][i] = a[i] * b[i];
        c[i] = c[i - 1] + a[i] * b[i];
    }


    for ( i = 1, sum = c[n]; i < n; i++ )
    {
        for ( j = 1; j <= n - i; j++ )
        {
            t = c[j - 1] + c[n] - c[j + i];
            dp[i + 1][j] =  a[j] * b[j + i] + a[j + i] * b[j]  + dp[i - 1][j + 1];
            sum = sum < dp[i + 1][j] + t ? dp[i + 1][j] + t : sum;
        }
    }

    cout << sum << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GUESSERR

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值