【斜率优化】[BZOJ3437] 小P的牧场

来源:互联网 发布:寻路算法 编辑:程序博客网 时间:2024/05/01 10:59

模板题,不用多说,只不过本地测,cin 2.6s,scanf 0.6s过。确实数据大了还是少用cin.

#include<cstdio>#include<algorithm>#include<cmath>#include<iostream>#include<cstring>#define MAXN 1000000using namespace std;#define gx(i) (sum[i])#define gy(i) (d[i] + sumt[i])typedef long long LL;//!!!!int a[MAXN +10];int b[MAXN +10];int que[MAXN +10];LL sumt[MAXN +10];//t[i] = b[i] * i;LL sum[MAXN +10];LL d[MAXN +10];LL get_d(LL i,LL j){return d[j] + i * (sum[i] - sum[j]) - (sumt[i] - sumt[j]) + a[i];}int main(){//freopen("farm.in","r",stdin);//freopen("farm.out","w",stdout);LL i,f,r,x1,x2,y1,y2,n;cin >> n;for(i = 1;i <= n;i++)scanf("%d",&a[i]);for(i = 1;i <= n;i++)scanf("%d",&b[i]);for(i = 1;i <= n;i++){sumt[i] = sumt[i - 1] + b[i] * i;sum[i] = sum[i - 1] + b[i];}f = r = que[0] = 0;for(i = 1;i <= n;i++){LL tmp = i - 1;while(f < r){x1 = gx(que[r]) - gx(que[r-1]);y1 = gy(que[r]) - gy(que[r-1]);x2 = gx(tmp) - gx(que[r]);y2 = gy(tmp) - gy(que[r]);if(y1 * x2 >= y2 * x1)r--;else break;}que[++r] = tmp;while(f < r && get_d(i,que[f]) > get_d(i,que[f + 1]))f++;d[i] = get_d(i,que[f]);}cout << d[n] << endl;//printf("%d\n",d[n]);}/*42 4 2 43 1 4 2*/

0 0