CF EDU 108 D - Maximum Sum of Products
D - Maximum Sum of Products
区间DP
可先算出不反转任何子区间的答案 \(sum\)
再利用 区间DP 算出反转 \([l,r]\) 的话会比原来的答案多多少,记为 \(f[l][r]\)
转移:\(f[l][r]=f[l+1][r-1]+a[l]*b[r]+a[r]*b[l]-a[l]*b[l]-a[r]*b[r]\)
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 5e3 + 10;
int n;
ll f[N][N];
ll a[N], b[N], sum;
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
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 = 1; i < n; i++) f[i][i+1] = a[i] * b[i+1] + a[i+1] * b[i] - a[i] * b[i] - a[i+1] * b[i+1];
for (int len = 3; len <= n; len++)
{
for (int l = 1; l + len - 1 <= n; l++)
{
int r = l + len - 1;
f[l][r] = f[l+1][r-1] + a[l] * b[r] + a[r] * b[l] - a[l] * b[l] - a[r] * b[r];
}
}
ll add = 0;
for (int len = 2; len <= n; len++)
{
for (int l = 1; l + len - 1 <= n; l++)
{
int r = l + len - 1;
add = max(add, f[l][r]);
}
}
cout << sum + add << endl;
return 0;
}