【DP】 BZOJ 3437: 小P的牧场

来源:互联网 发布:网络神偷电影电视剧 编辑:程序博客网 时间:2024/05/01 09:28

斜率优化一下就行了。。。

#include <bits/stdc++.h>using namespace std;typedef long long LL;const int maxn = 1000005;LL a[maxn], H[maxn], s[maxn], f[maxn];int q[maxn], n, m;LL getfz(int j2, int j1){return f[j1] - f[j2] + H[j1] - H[j2];}LL getfm(int j2, int j1){return s[j1] - s[j2];}LL getf(int i, int j){return f[j] + a[i] + i * s[i] - i * s[j] - H[i] + H[j];}void work(){for(int i = 1; i <= n; i++) scanf("%lld", &a[i]);for(int i = 1; i <= n; i++) {scanf("%lld", &s[i]);H[i] = i * s[i];s[i] += s[i-1];H[i] += H[i-1];}f[0] = 0;int h = 0, r = 0;q[r++] = 0;for(int i = 1; i <= n; i++) {while(r - h > 1 && getfz(q[h], q[h+1]) <= i * getfm(q[h], q[h+1])) h++;f[i] = getf(i, q[h]);while(r - h > 1 && getfz(q[r-1], i) * getfm(q[r-2], q[r-1]) <= getfz(q[r-2], q[r-1]) * getfm(q[r-1], i)) r--;q[r++] = i;}printf("%lld\n", f[n]);}int main(){//freopen("data", "r", stdin);while(scanf("%d", &n) != EOF) {work();}return 0;}


0 0