3437: 小P的牧场
思路
斜率优化。
dp[i]表示到第i个点(第i个点按控制台)的最小代价。
代码
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],a[N],b[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*(b[i]-b[j])); 19 } 20 int main() { 21 int n = read(); 22 for (int i=1; i<=n; ++i) a[i] = read(); 23 for (int i=1; i<=n; ++i) { 24 b[i] = read(); 25 s[i] = s[i-1] + 1ll * b[i] * i; 26 b[i] += b[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)i) L++; 32 int j = q[L]; 33 f[i] = f[j] + i * (b[i-1] - b[j]) - (s[i-1] - s[j]) + a[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 }
原文地址:https://www.cnblogs.com/mjtcn/p/8977314.html
时间: 2024-10-07 09:05:21