3437: 小P的牧场

时间:2022-12-07 12:29:20

3437: 小P的牧场

思路

  斜率优化。

  dp[i]表示到第i个点(第i个点按控制台)的最小代价。

代码

 #include<cstdio>
#include<iostream> using namespace std;
typedef long long LL; const int N = ;
LL f[N],s[N],a[N],b[N];
int q[N],L,R; inline int read() {
int x = ,f = ;char ch = getchar();
for (; !isdigit(ch); ch=getchar()) if(ch=='-') f=-;
for (; isdigit(ch); ch=getchar()) x = x*+ch-'';
return x * f;
}
double Slope(int i,int j) {
return 1.0*(f[i]+s[i]-f[j]-s[j])/(1.0*(b[i]-b[j]));
}
int main() {
int n = read();
for (int i=; i<=n; ++i) a[i] = read();
for (int i=; i<=n; ++i) {
b[i] = read();
s[i] = s[i-] + 1ll * b[i] * i;
b[i] += b[i-]; // 顺序不能反!
}
int L = ,R = ;
q[] = ;
for (int i=; i<=n; ++i) {
while (L<R && Slope(q[L],q[L+]) < (double)i) L++;
int j = q[L];
f[i] = f[j] + i * (b[i-] - b[j]) - (s[i-] - s[j]) + a[i];
while (L<R && Slope(q[R-],q[R]) > Slope(q[R],i)) R--;
q[++R] = i;
}
cout << f[n];
return ;
}