CEOI 2004 锯木场选址(DP + 斜率优化经典)
题意:
有 n 棵树,从山顶排到山脚,山脚下有个伐木场,你也可以在路上建两个伐木场,问将所有树砍下运到伐木场的最小费用,树只能往下运。
题目链接:http://cojs.tk/cogs/problem/problem.php?pid=362
思路:
1. “用单调性优化动态规划”论文中有关于类似题目的论述,不过公式不太一样,本题需要自行推导;
2. 代码中变量的定义说明:w[i] 表示 1~i 树木重量总和,x[i] 表示树木 i 距离树木 1 的距离;(推导过程中 w 为树重量,sumw 为1~i 树木重量总和);
3. F(i) = w1 * (xj - x1) + w2 * (xj - x2) + ... + wj * (xj - xj)
+ wj+1 * (xi - xj+1) + wj+2 * (xi - xj+2) + ... + wi * (xi - xi)
+ wi+1 * (xn+1 - xi+1) + wi+2 * (xn+1 - xi+2) + ... + wn * (xn+1 - xn);
4. 化简可得:F(i) = delta + Y - a * X; 其中 a = xi, X = sumwj, Y = sumwj * xj
5. 由公式可以看出当 i 固定时,delta, a 为常数,对于 X, Y 选定一点使 F(i) 最小即可。对于 X, Y 可以利用下凸函数的特性,用队列来维护,具体就不阐述了。
#include <iostream>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int MAXN = 20010;
const int INFS = 0x7fffffff;
int w[MAXN], d[MAXN], x[MAXN], deq[MAXN];
inline double slope(int i, int j)
{
return 1.0 * (w[i] * x[i] - w[j] * x[j]) / (w[i] - w[j]);
}
int main()
{
freopen("two.in","r",stdin);
freopen("two.out","w",stdout);
int n;
scanf("%d\n", &n);
for (int i = 1; i <= n; ++i)
scanf("%d %d", &w[i], &d[i]);
w[0] = d[0] = x[1] = 0;
int sum = 0;
for (int i = 1; i <= n; ++i)
{
x[i+1] = x[i] + d[i];
sum += x[i] * w[i], w[i] += w[i-1];
}
int ans = INFS;
int s = 0, e = -1;
for (int i = 1; i <= n; ++i)
{
while (s < e && slope(deq[e], deq[e-1]) >= slope(i, deq[e]))
--e;
deq[++e] = i;
while (s < e && slope(deq[s], deq[s+1]) <= x[i])
++s;
int delta = -sum + w[i] * x[i] + (w[n] - w[i]) * x[n+1];
ans = min(ans, delta + w[deq[s]] * x[deq[s]] - x[i] * w[deq[s]]);
}
printf("%d\n", ans);
fclose(stdin);
fclose(stdout);
return 0;
}
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------