思路:
平形四边形不等式优化dp
同上一篇博客
代码:
#pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize(4) #include<iostream> #include<cstdio> #include<cstring> using namespace std; #define y1 y11 #define fi first #define se second #define pi acos(-1.0) #define LL long long #define LD long double //#define mp make_pair #define pb push_back #define ls rt<<1, l, m #define rs rt<<1|1, m+1, r #define ULL unsigned LL #define pll pair<LL, LL> #define pli pair<LL, int> #define pii pair<int, int> #define piii pair<int, pii> #define pdd pair<long double, long double> #define mem(a, b) memset(a, b, sizeof(a)) #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); //head const int N = 1e3 + 5; LL dp[N][N], w[N][N]; int n, m, s[N][N], a[N]; int main() { while(~scanf("%d %d", &n, &m) && n && m) { for (int i = 1; i <= n; ++i) scanf("%d", &a[i]); for (int i = 0; i <= m+1; ++i) for (int j = 0; j <= n; ++j) dp[i][j] = 1LL<<58; for (int i = 1; i <= n; ++i) { w[i][i] = 0; int s = a[i]; for (int j = i+1; j <= n; ++j) { w[i][j] = w[i][j-1]+s*a[j]; s += a[j]; } } dp[0][0] = 0; for (int i = 1; i <= m+1; ++i) { w[i][n+1] = n-1; for (int j = n; j >= 1; --j) { for (int k = w[i-1][j]; k <= w[i][j+1]; ++k) { if(k+1 <= j && dp[i-1][k]+w[k+1][j] < dp[i][j]) { dp[i][j] = dp[i-1][k]+w[k+1][j]; w[i][j] = k; } } } } printf("%d ", dp[m+1][n]); } return 0; }