[APIO2014]序列分割

嘟嘟嘟


复习一下斜率优化,感觉已经忘得差不多了……


这题切入点在与答案跟切的顺序无关
证明就是假如有三段权值分别为\(x, y, z\),那么这两刀不管按什么顺序切,得到的结果都是\(xy + xz + yz\)


然后就可以dp。
\(dp[i][j]\)表示前\(i\)个数切\(j\)刀的最大得分,于是就有\(dp[i][j] = max\{ dp[k][j - 1] + s[k] * (s[i] - s[k]) \}\)
观察这个式子,发现\(j\)只能从\(j - 1\)转移过来,那索性把\(j\)换到第一维,然后就可以滚动数组省去第一维了,即\(f[i] = max \{ g[k] + s[k] * (s[i] - s[k]) \}\)
看到乘积,似乎能想到斜率优化。于是假设\(t_2 > t_1\),且\(t_2\)的决策比\(t_1\)优,这时候\(t_1\)就可以扔掉了。那么就有

\[\begin{align*} g[t_2] + s[t_2] * (s[i] - s[t_2]) &\geqslant g[t_1] + s[t_1] * (s[i] - s[t_1]) \\ \frac{(g[t_1] - s[t_1] ^ 2) - (g[t_2] - s[t_2] ^ 2)}{g[t_2] - g[t_1]} &\leqslant s[i] \end{align*}\]

于是我们用单调队列维护一个下凸壳就好啦。


坑点在于\(s[t_1] = s[t_2]\),这时候斜率直接返回\(-INF\),把\(t_1\)扔出去。


彩蛋:某谷第12个点卡精度,然后我发现乘以\(1.0\)比强制类型转换成double精度要高……

#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 In inline
typedef long long ll;
typedef double db;
const ll INF = 1e18;
const db eps = 1e-8;
const int maxn = 2e5 + 5;
const int maxm = 205;
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, K;
ll a[maxn];
ll sum[maxn], f[maxn], g[maxn];
int q[maxn], pre[maxn][maxm];

In db slope(int i, int j)
{
  if(sum[i] == sum[j]) return -INF;
  return 1.0 * ((g[i] - sum[i] * sum[i]) - (g[j] - sum[j] * sum[j])) / ((db)sum[j] - sum[i]);
}

int main()
{
  n = read(), K = read();
  for(int i = 1; i <= n; ++i) a[i] = read(), sum[i] = sum[i - 1] + a[i];
  for(int j = 1; j <= K; ++j)
    {
      int l = 1, r = 0;
      q[++r] = 0;
      for(int i = 1; i <= n; ++i)
	{
	  while(l < r && slope(q[l], q[l + 1]) <= sum[i]) ++l;
	  f[i] = g[q[l]] + sum[q[l]] * (sum[i] - sum[q[l]]);
	  pre[i][j] = q[l];
	  while(l < r && slope(q[r - 1], q[r]) >= slope(q[r], i)) --r;
	  q[++r] = i;
	}
      memcpy(g, f, sizeof(f));
    }
  write(f[n]), enter;
  for(int j = n, i = K; i; --i) j = pre[j][i], write(j), space; enter;
  return 0;
}
posted @ 2019-04-25 10:00  mrclr  阅读(187)  评论(0编辑  收藏  举报