BZOJ3156 防御准备

本文介绍了一种使用动态规划优化斜率的方法解决防御塔布局问题。通过数学推导简化了状态转移方程,并实现了时间复杂度为O(n)的算法。代码中详细展示了算法的具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Solution]

Long time not writing anything.

It seems like a DP problem, and it actually is. We can easily come up with the equation that

f[i] = min(f[j] + (j - i) * (j - i - 1) / 2) + a[i]

f[i] means the lowest cost setting a defence tower at the ith position.

That equation means O(n^2) time of state transferring. However, we can simplify it into this

i * j - i * (i - 1) / 2 - a[i] + f[i] = f[j] + j * (j + 1) / 2

That's a equation that wew can set the right part as Y and j as X. We need to find the minimal f[i], which means the intercept of the function should be minimal. That's obviously a DP optimized by slope.


[Code]

#include <cstdio>
#include <memory.h>
#include <ctype.h>
#include <algorithm>

using namespace std;

typedef long double llf;
typedef long long qw;

#ifdef WIN32
#define lld "%I64d"
#else
#define lld "%lld"
#endif
#define _l (qw)

int nextInt() {
	int d, s = 0;
	do
		d = getchar();
	while (!isdigit(d));
	do
		s = s * 10 + d - 48, d = getchar();
	while (isdigit(d));
	return s;
}

const int maxn = 1000010;

int n, a[maxn], q[maxn], hd, tl;
qw f[maxn], ans;

inline qw gety(int x) {
	return f[x] + _l x * (x + 1) / 2;
}

inline llf getk(int i, int j) {
	return ((llf)gety(j) - gety(i)) / ((llf)j - i);
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif

	n = nextInt();
	for (int i = 0; i < n; i ++)
		a[n - i - 1] = nextInt();
	f[0] = a[0];
	hd = 0, tl = 1;
	q[hd] = 0;
	ans = a[0] + _l n * (n - 1) / 2;
	for (int i = 1; i < n; i ++) {
		while (hd + 2 < tl && getk(q[hd], q[hd + 1]) < (llf)i)
			hd ++;
		f[i] = gety(q[hd]) - _l i * q[hd] + _l i * (i - 1) / 2 + a[i];
		ans = min(ans, f[i] + (_l n - i) * (_l n - i - 1) / 2);
		q[tl] = i;
		while (hd + 2 <= tl && getk(q[tl - 1], q[tl]) < getk(q[tl - 2], q[tl - 1]))
			q[tl - 1] = q[tl], tl --;
		tl ++;
	}
	printf(lld "\n", ans);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值