D 两串糖果
区间DP


分析:
很容易想到一个暴力的dp。
定义dp[i],表示讲区间[1,i]处理完后的最大值。
转移方程很容易想到dp[i] = max(dp[i],dp[i - j] + sum[i - j + 1][i])
sum[i][j]表示操作区间[l,r]后的贡献。
很明显需要与处理出sum[i][j],这样转移的复杂度是$O(n^2)$
接下来考虑预处理sum[i][j]
暴力预处理是$O(n^3)$的,我们考虑区间dp,sum[i][j] = sum[i+1][j-1] + ar[i]*br[j] + ar[j]*br[i]
这样就可以$O(n^2)$预处理,算法总体复杂度$O(n^2)$
另外,尤其需要注意,区间dp应当先枚举区间长度。
AC代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <bits/stdc++.h>
using namespace std; typedef long long ll; #define int ll #define io ios::sync_with_stdio(false),cin.tie(0),cout.tie(0) #define endl '\n' #define itt set<node>::iterator
const int maxn = 5e3 + 5; const ll mod = 1e9 + 7; const ll inf = 0x3f3f3f3f; int ar[maxn], br[maxn]; int dp[maxn], sum[maxn][maxn]; int n;
signed main() { io; cin >> n; for(int i = 1; i <= n; ++i) cin >> ar[i]; for(int i = 1; i <= n; ++i) cin >> br[i];
for(int i = 1; i <= n; ++i) { sum[i][i] = ar[i] * br[i]; if(i != n) sum[i][i + 1] = ar[i] * br[i + 1] + ar[i + 1] * br[i]; }
int r; for(int i = 3; i <= n; ++i) { for(int l = 1; l <= n; ++l) { r = l + i - 1; if(r > n) break; sum[l][r] = sum[l + 1][r - 1] + ar[l] * br[r] + ar[r] * br[l]; } }
for(int i = 1; i <= n; ++i) { for(int j = 1; j <= i; ++j) { dp[i] = max(dp[i], dp[i - j] + sum[i - j + 1][i]); } }
cout << dp[n] << '\n';
return 0; }
|