输入样例:
4
1 3 5 2
输出样例:
22
#include <bits/stdc++.h>
using namespace std;
const int N = 5010;
int n;
int a[N];
int f[N][N];
int p[N][N];//f[i][j]的最优决策
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i];
a[i] += a[i - 1];
p[i][i] = i;//初始化
}
for(int l = 2; l <= n; l++){
for(int i = 1; i <= n; i++){
int j = i + l - 1;
f[i][j] = 1e8;
for(int k = p[i][j - 1]; k <= p[i + 1][j]; k++){
int t = f[i][k] + f[k + 1][j] + a[j] - a[i - 1];
if(t < f[i][j]){
f[i][j] = t;
p[i][j] = k;
}
}
}
}
cout << f[1][n];
return 0;
}
二维不等式优化问题的推导可以去看bilibili的讲解。