1911: [Apio2010]特别行动队(斜率优化)
思路
斜率优化dp。
代码
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 #include<iostream> 5 #include<cmath> 6 7 using namespace std; 8 typedef long long LL; 9 int n,L,R; 10 LL A,B,C,s[1000100],q[1000100],f[1000100]; 11 12 inline int read() { 13 int x = 0,f = 1;char ch = getchar(); 14 for (; !isdigit(ch); ch=getchar()) if(ch=='-') f=-1; 15 for (; isdigit(ch); ch=getchar()) x = x*10+ch-'0'; 16 return x * f; 17 } 18 double Y(int x) { 19 return double(f[x]+A*s[x]*s[x]-B*s[x]); 20 } 21 double slope(int i,int j) { 22 return (Y(i)-Y(j))/double(s[i]-s[j]); 23 } 24 int main() { 25 n = read(),A = read(),B = read(),C = read(); 26 for (int i=1; i<=n; ++i) s[i] = read(),s[i] += s[i-1]; 27 28 int L = 1,R = 0; 29 q[++R] = 0; 30 for (int i=1; i<=n; ++i) { 31 while (L<R && slope(q[L],q[L+1])>2.0*A*s[i]) L++; 32 int j = q[L]; 33 f[i] = f[j]+A*(s[i]-s[j])*(s[i]-s[j])+B*(s[i]-s[j])+C; 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 }