题解 P3195 【[HNOI2008]玩具装箱TOY】
容易推出,如果玩具长度的前缀和为
此时
可得
决策单调性实现即,用一个栈维护每个决策的起始和结束位置。对于每个已经计算出来的
具体为:
(1)在栈顶的决策起始位置判断起始位置是否决策
(2)二分查找在栈顶的决策区间里,决策
代码:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
typedef long long ll;
const int N = 5e4 + 5;
int n, L, c[N], top; ll sm[N], f[N];
struct cyx {
int l, r, x;
cyx() {}
cyx(int _l, int _r, int _x) :
l(_l), r(_r), x(_x) {}
} stk[N];
ll w(int i, int j) {
ll res = sm[j] - sm[i] - L;
res += j - i - 1; return res * res;
}
int findx(int i) {
int l = stk[top].l, r = stk[top].r, mid;
while (l <= r) { // 二分查找新决策的起始位置
mid = l + r >> 1;
if (f[i] + w(i, mid) < f[stk[top].x] + w(stk[top].x, mid))
r = mid - 1;
else l = mid + 1;
}
return l;
}
int main() {
int i, now = 1; n = read(); L = read();
for (i = 1; i <= n; i++) c[i] = read(),
sm[i] = sm[i - 1] + c[i];
stk[top = 1] = cyx(1, n, 0);
for (i = 1; i <= n; i++) {
f[i] = f[stk[now].x] + w(stk[now].x, i);
while (i < stk[top].l && f[i] + w(i, stk[top].l) < f[stk[top].x] +
w(stk[top].x, stk[top].l)) top--;
int u = findx(i); stk[top].r = u - 1;
if (u <= n) stk[++top] = cyx(u, n, i);
if (i == stk[now].r) now++;
}
cout << f[n] << endl;
return 0;
}
时间复杂度
解法二:斜率优化。
可以发现原方程为
设
则
即
再设
则可以发现
代码:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
typedef long long ll;
const int N = 5e4 + 5;
int n, H, T, L, que[N];
ll f[N], a[N], b[N], X[N], Y[N];
bool check(int p1, int p2, int p3) {
return (X[p2] - X[p3]) * (Y[p1] - Y[p3]) - (X[p1] - X[p3])
* (Y[p2] - Y[p3]) >= 0; // 根据叉积判断p1p2的斜率是否大于p2p3的斜率
}
ll calc(int x, int y) {
return f[x] + b[x] * b[x] - 2ll * a[y] * b[x];
}
int main() {
int i; n = read(); L = read(); H = T = 1;
for (i = 1; i <= n; i++) {
b[i] = b[i - 1] + read() + 1;
a[i] = b[i] - L - 1;
}
for (i = 1; i <= n; i++) {
while (H < T && calc(que[H], i) >= calc(que[H + 1], i)) H++;
f[i] = calc(que[H], i) + a[i] * a[i];
X[i] = b[i]; Y[i] = f[i] + b[i] * b[i];
while (H < T && check(que[T - 1], que[T], i)) T--;
que[++T] = i;
}
cout << f[n] << endl;
return 0;
}
时间复杂度