把dp方程列出来, 把所有东西拆成前缀的形式, 就能看出可以斜率优化啦。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ull unsigned long long using namespace std; const int N = 2e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); int n, k, be, ed, que[N]; double sum[N], prefix[N], dp[N][51], t[N]; double calc(int k, int j, int c) { return ((dp[j][c] + sum[j] * prefix[j]) - (dp[k][c] + sum[k] * prefix[k])) / (sum[j] - sum[k]); } int main() { be = 1, ed = 0; scanf("%d%d", &n, &k); for(int i = 1; i <= n; i++) scanf("%lf", &t[i]); for(int i = 1; i <= n; i++) prefix[i] = prefix[i - 1] + 1 / t[i]; for(int i = 1; i <= n; i++) sum[i] = sum[i - 1] + t[i]; dp[0][0] = 0; que[++ed] = 0; for(int j = 1; j <= k; j++) { int p = j - 1; for(int i = j; i <= n; i++) { while(j > 1 && p < i) { while(ed - be + 1 >= 2 && calc(que[ed-1], que[ed], j-1) > calc(que[ed], p, j-1)) ed--; que[++ed] = p; p++; } while(ed - be + 1 >= 2 && calc(que[be], que[be+1], j-1) < prefix[i]) be++; int who = que[be]; dp[i][j] = dp[who][j - 1] - sum[who] * (prefix[i] - prefix[who]); } be = 1; ed = 0; } double ans = dp[n][k]; for(int i = 1; i <= n; i++) ans += sum[i] / t[i]; printf("%.12f ", ans); return 0; } /* */