1096: [ZJOI2007]仓库建设
思路
斜率优化。
代码
1 #include<cstdio> 2 #include<iostream> 3 4 using namespace std; 5 typedef long long LL; 6 7 const int N = 1000100; 8 LL f[N],s[N],x[N],p[N],c[N]; 9 int q[N],L,R; 10 11 inline int read() { 12 int x = 0,f = 1;char ch = getchar(); 13 for (; !isdigit(ch); ch=getchar()) if(ch=='-') f=-1; 14 for (; isdigit(ch); ch=getchar()) x = x*10+ch-'0'; 15 return x * f; 16 } 17 double Slope(int i,int j) { 18 return 1.0*(f[i]+s[i]-f[j]-s[j])/(1.0*(p[i]-p[j])); 19 } 20 int main() { 21 int n = read(); 22 for (int i=1; i<=n; ++i) 23 x[i] = read(),p[i] = read(),c[i] = read(); 24 for (int i=1; i<=n; ++i) { 25 s[i] = s[i-1] + 1ll * x[i] * p[i]; 26 p[i] += p[i-1]; 27 } 28 int L = 1,R = 1; 29 q[1] = 0; 30 for (int i=1; i<=n; ++i) { 31 while (L<R && Slope(q[L],q[L+1]) < (double)x[i]) L++; 32 int j = q[L]; 33 f[i] = f[j] + x[i] * (p[i-1] - p[j]) - (s[i-1] - s[j]) + c[i]; 34 while (L<R && Slope(q[R-1],q[R]) > Slope(q[R],i)) R--; 35 q[++R] = i; 36 } 37 cout << f[n]; 38 return 0; 39 }