[ZJOI2007]仓库建设

嘟嘟嘟


刚开始推了一个\(O(n ^ 2)\)的dp方程,但是需要倒着来,然后斜率优化的时候出现了各种错误,最终还是放弃。
换一个正着来的吧。
\(dp[i]\)表示在\(i\)建仓库时的最小花费,则

\[dp[i] = min _ {j = 0} ^ {i} \{dp[j] + \sum _ {k = j + 1} ^ {i} {p[k] * (x[i] - x[k])}\} + c[i] \]

把里面的\(\sum\)拆开,得到\(x[i] * \sum _ {k = j + 1} ^ {i} p[k] - \sum _ {k = j + 1} ^ {i} d_k * p_k\),发现这个可以用两个前缀和优化到\(O(1)\)
于是

\[dp[i] = min _ {j = 0} ^ {i} \{dp[j] + x[i] * (sump[i] - sump[j]) - (sum[i] - sum[j])\} + c[i] \]

然后就是正常的斜率优化了。
简单导一导,得到
\(y = dp[j] + sum[j]\)
\(k = x[i]\)
\(x = sump[j]\)
\(dp[i] = y - kx + d[i] * sump[i] - sum[i] + c[i]\)
发现\(x, k\)都是单调递增,很开心,维护下凸包即可。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e6 + 5;
inline ll read()
{
  ll ans = 0;
  char ch = getchar(), last = ' ';
  while(!isdigit(ch)) last = ch, ch = getchar();
  while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
  if(last == '-') ans = -ans;
  return ans;
}
inline void write(ll x)
{
  if(x < 0) x = -x, putchar('-');
  if(x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}

int n, d[maxn], p[maxn], c[maxn];
ll sump[maxn], sum[maxn], dp[maxn];
int q[maxn], l = 0, r = 0;

#define k(i) d[i]
#define x(i) sump[i]
#define y(i) (dp[i] + sum[i])
db slope(int i, int j)
{
  return 1.0 * (y(i) - y(j)) / (x(i) - x(j));
}

int main()
{
  n = read();
  for(int i = 1; i <= n; ++i)
    {
      d[i] = read(), p[i] = read(), c[i] = read();
      sump[i] = sump[i - 1] + p[i];
      sum[i] = sum[i - 1] + (ll)d[i] * p[i];
    }
  for(int i = 1; i <= n; ++i)
    {
      while(l < r && slope(q[l], q[l + 1]) < k(i)) ++l;
      dp[i] = y(q[l]) - k(i) * x(q[l]) + d[i] * sump[i] - sum[i] + c[i];
      while(l < r && slope(q[r], q[r - 1]) > slope(q[r], i)) --r;
      q[++r] = i;
    }
  write(dp[n]), enter;
  return 0;
}
posted @ 2018-12-17 17:13  mrclr  阅读(145)  评论(0编辑  收藏  举报