BZOJ1010: [HNOI2008]玩具装箱toy

1010: [HNOI2008]玩具装箱toy

Time Limit: 1 Sec Memory Limit: 162 MB

Submit: 12084 Solved: 5173

Description

P教授要去看奥运,但是他舍不下他的玩具,于是他决定把所有的玩具运到北京。他使用自己的压缩器进行压
缩,其可以将任意物品变成一堆,再放到一种特殊的一维容器中。P教授有编号为1...N的N件玩具,第i件玩具经过
压缩后变成一维长度为Ci.为了方便整理,P教授要求在一个一维容器中的玩具编号是连续的。同时如果一个一维容
器中有多个玩具,那么两件玩具之间要加入一个单位长度的填充物,形式地说如果将第i件玩具到第j个玩具放到一
个容器中,那么容器的长度将为 x=j-i+Sigma(Ck) i<=K<=j 制作容器的费用与容器的长度有关,根据教授研究,
如果容器长度为x,其制作费用为(X-L)^2.其中L是一个常量。P教授不关心容器的数目,他可以制作出任意长度的容
器,甚至超过L。但他希望费用最小.

Input

第一行输入两个整数N,L.接下来N行输入Ci.1<=N<=50000,1<=L,Ci<=10^7

Output

输出最小费用

Sample Input

5 4
3
4
2
1
4

Sample Output

1

题解

斜率优化入门题。
不难写出转移方程(dp[i] = min{dp[j] + (i - j - l - L + sum[i] - sum[j])^2}),其中(sum[i] = sum^{i}_{j = 1}c[i])
(c = L + 1)(h[i] = sum[i] + i),去掉min,化简得到(化错了三次。。。还以为程序错了。耽误了好久)
((h[j] + c)^2 + dp[j] = 2h[i](h[j] + c) + dp[i] - h^2[i])
(y =(h[j] + c)^2 + dp[j]),(k = 2h[i]),(x = h[j] + c),(b = dp[i] - h^2[i])
得到(y = kx + b)的形式。不难发现x和k都是单调递增的。
单调队列维护即可(想清楚边界即可,比如(0,0))。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <map>
#include <string> 
#include <cmath> 
#include <sstream>
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define abs(a) ((a) < 0 ? (-1 * (a)) : (a))
template<class T>
inline void swap(T &a, T &b)
{
	T tmp = a;a = b;b = tmp;
}
inline void read(long long &x)
{
    x = 0;char ch = getchar(), c = ch;
    while(ch < '0' || ch > '9') c = ch, ch = getchar();
    while(ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar();
    if(c == '-') x = -x;
}
const long long INF = 0x3f3f3f3f;
const long long MAXN = 100000 + 10;
long long dp[MAXN], q[MAXN], he, ta, sum[MAXN], h[MAXN], n, L, c[MAXN];
inline long long y(long long j)
{
	return (h[j] + L + 1) * (h[j] + L + 1) + dp[j];
}
inline long long x(long long i)
{
	return h[i] + L + 1;
} 
//点i与点j的斜率 
inline long long s(long long i, long long j)
{
	return (y(i) - y(j)) / (x(i) - x(j));
}
//当前决策i的斜率
inline long long s(long long i)
{
	return 2 * h[i];
} 
int  main()
{
	freopen("data.txt", "r", stdin);
	read(n), read(L);
	for(long long i = 1;i <= n;++ i) read(c[i]), sum[i] = sum[i - 1] + c[i], h[i] = sum[i] + i;
	he = ta = 0;
	for(long long i = 1;i <= n;++ i)
	{
		while(he < ta && s(i) > s(q[he], q[he + 1])) ++ he;
		dp[i] = y(q[he]) - s(i) * x(q[he]) + h[i] * h[i];
		while(he < ta && s(q[ta], i) < s(q[ta - 1], q[ta])) -- ta;
		q[++ ta] = i;
	}
	printf("%lld", dp[n]);
	return 0;
}
原文地址:https://www.cnblogs.com/huibixiaoxing/p/8410769.html