翻译:
给出两个长度为𝑛的整数数组𝑎和𝑏。
您最多可以反转数组𝑎的一个子数组(连续子段)。
你的任务是反转这样的子数组,使∑𝑖=1𝑛𝑎𝑖⋅𝑏𝑖最大化。
输入
第一行包含一个整数𝑛(1≤𝑛≤5000)。
第二行包含𝑛整数𝑎1𝑎2,…,𝑎𝑛(1≤𝑎𝑖≤107)。
第三行包含𝑛整数𝑏1𝑏2,…,𝑏𝑛(1≤𝑏𝑖≤107)。
输出
打印单个整数-反转𝑎的最多一个子数组(连续子段)后的最大可能和。
例子
inputCopy
5
2 3 2 1 3
1 3 2 4 2
outputCopy
29
inputCopy
2
13 37
2 4
outputCopy
174
inputCopy
6
1 8 7 6 3 6
5 9 6 8 8 6
outputCopy
235
请注意
在第一个例子中,您可以反向子数组[4,5]。那么𝑎=[2,3,2,3,1]和2⋅1+3⋅3+2⋅2+3⋅4+1⋅2=29。
在第二个示例中,不需要使用反向操作。13 37⋅⋅2 + 4 = 174。
在第三个例子中,您可以反转子数组[3,5]。然后𝑎=[1、8、3、6、7、6]和1⋅5 + 8⋅9 + 3⋅6 + 6⋅8 + 7⋅8 + 6⋅6 = 235。
思路:
大致看了下题,就是区间翻转,这题的时间复杂度应该是n^2级别的,所以我们只需要思考如何On,枚举一个点的所有情况即可,刚开始以为直接当左端点然后每次向右边拓展,后来发现,改变的值还需要改变过来,再来翻转改变,同理右端点也是。每次翻转两边,向两边扩展,枚举点作为中心点好像是可以的,每次改变值的累加都是可以用在下一次的,所以我们减去原来的值,加上新值,也可以用前缀和预处理来写。翻转分奇偶的情况,所以我们枚举两种即可。
代码:
#include <iostream>
#include <algorithm>
#include <string.h>
#include <string>
#include <math.h>
#include <stdio.h>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<tuple>
#include<numeric>
using namespace::std;
typedef long long ll;
inline __int128 read(){
__int128 x = 0, f = 1;
char ch = getchar();
while(ch < '0' || ch > '9'){
if(ch == '-')
f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9'){
x = x * 10 + ch - '0';
ch = getchar();
}
return x * f;
}
inline void print(__int128 x){
if(x < 0){
putchar('-');
x = -x;
}
if(x > 9)
print(x / 10);
putchar(x % 10 + '0');
}
int n;
ll a[5005],b[5005],an[5005],su,ans;
int main(){
ios::sync_with_stdio(false);
cin.tie(); cout.tie();
cin>>n;
for (int i =1; i<=n; i++) {
cin>>a[i];
}
for (int i =1; i<=n; i++) {
cin>>b[i];
an[i]=an[i-1]+a[i]*b[i];
}
ans=an[n];
for (int i =1; i<=n; i++) {
int k=i;
su=0;
for (int l=i-1,r=i+1; l>=1&&r<=n; l--,r++) {
su+=a[l]*b[r];
su+=a[r]*b[l];
ans=max(ans,su+an[n]-an[r]+an[l-1]+a[i]*b[i]);
}
su=0;
for (int l=i,r=i+1; l>=1&&r<=n;l--,r++) {
su+=a[l]*b[r];
su+=a[r]*b[l];
ans=max(ans,su+an[n]-an[r]+an[l-1]);
}
}
printf("%lld\n",ans);
return 0;
}