题目链接Problem - 1519D - Codeforces
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 aa and bb of length nn.
You can reverse at most one subarray (continuous subsegment) of the array aa.
Your task is to reverse such a subarray that the sum ∑i=1nai⋅bi∑i=1nai⋅bi is maximized.
Input
The first line contains one integer nn (1≤n≤50001≤n≤5000).
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).
The third line contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1071≤bi≤107).
Output
Print single integer — maximum possible sum after reversing at most one subarray (continuous subsegment) of aa.
Examples
input
Copy
5 2 3 2 1 3 1 3 2 4 2
output
Copy
29
input
Copy
2 13 37 2 4
output
Copy
174
input
Copy
6 1 8 7 6 3 6 5 9 6 8 8 6
output
Copy
235
Note
In the first example, you can reverse the subarray [4,5][4,5]. Then a=[2,3,2,3,1]a=[2,3,2,3,1] and 2⋅1+3⋅3+2⋅2+3⋅4+1⋅2=292⋅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=17413⋅2+37⋅4=174.
In the third example, you can reverse the subarray [3,5][3,5]. Then a=[1,8,3,6,7,6]a=[1,8,3,6,7,6] and 1⋅5+8⋅9+3⋅6+6⋅8+7⋅8+6⋅6=2351⋅5+8⋅9+3⋅6+6⋅8+7⋅8+6⋅6=235.
---------------------------------------------------------------------------------------------------------------------------------
首先,普通模拟肯定是会tle,数据5000,考虑n^2做法
我们必须在n^2时间内找到全部可能的翻转区间,由于翻转区间是有翻转轴的,我们可以枚举翻转轴。而翻转轴可能是一个数 比如 1 2 3 4 5 中的3 也可能是 两个数 1 2 3 4 中的 2 3所以我们分别枚举奇偶情况,向两侧扩展即可。
ai-1 ai ai+1
bi-1 bi bi+1
翻转后减去翻转前 (a[k]-a[j])*(b[j])+(b[k])*(a[j]-a[k]);
再向两侧扩展时,在此基础上再加上新扩展的差即可
这样做,枚举每个旋转点,向两侧扩展,时间复杂度接近n^2,是可以过的
#include<iostream>
#include<stack>
#include<string>
using namespace std;
typedef long long int ll;
ll a[5010],b[5010];
int main ()
{
int n;
cin>>n;
ll sum=0;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int j=1;j<=n;j++)
{
cin>>b[j];
sum+=a[j]*b[j];
}
ll temp=0,ans=-999999999999;
for(int i=1;i<=n;i++)
{
temp=0;
for(int j=i, k=i;j>=1&&k<=n;k++,j--)
{
temp+=(a[k]-a[j])*(b[j])+(b[k])*(a[j]-a[k]);
ans=max(ans,temp);
}
}
for(int i=1;i<=n;i++)
{
temp=0;
for(int j=i,k=i+1;j>=1&&k<=n;k++,j--)
{
temp+=(a[k]-a[j])*(b[j])+(b[k])*(a[j]-a[k]);
ans=max(ans,temp);
}
}
cout<<sum+ans<<'\n';
return 0;
}