跳到正文

题解

题解:P3878 [TJOI2010] 分金币

zhangxiaoyu008约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月10日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 3 分钟
题目
P3878

版本

  1. v1当前

为什么会有折半状压和模拟退火,这不是个折半搜索的板子吗?

我们设第一部分的金币数目为 ⌊n2⌋\displaystyle\lfloor\frac{n}{2}\rfloor,第二部分的金币数目为 n−⌊n2⌋\displaystyle n - \lfloor\frac{n}{2}\rfloor。

容易发现,我们只需要在搜索时记录当前选到第一部分集合的数量,和当前第一部分集合的价值减掉第二部分集合的价值即可。

而且我们发现,这样跑的飞快啊,一共只用了 104ms

已过 Hack,而且仅用 106ms

Code\large{\mathbf{Code}}
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf = 1e18;
int T, n, a[40], k, ed, top[20];
ll f[20][32775], res;
void dfs(int u, int cnt, ll s) {
	if(u == k) {
		f[cnt][top[cnt] ++] = s;
		return;
	}
	dfs(u + 1, cnt + 1, s + a[u]);
	dfs(u + 1, cnt, s - a[u]);
}
void dfs2(int u, int cnt, ll s) {
	if(u == n) {
		if(cnt < 0) return;
		int pos = lower_bound(f[cnt], f[cnt] + top[cnt], s) - f[cnt];
		if(pos < top[cnt]) res = min(res, llabs(f[cnt][pos] - s));
		pos = upper_bound(f[cnt], f[cnt] + top[cnt], s) - f[cnt];
		if(!pos) return;
		pos --;
		res = min(res, llabs(f[cnt][pos] - s));
		return;
	}
	dfs2(u + 1, cnt - 1, s - a[u]);
	dfs2(u + 1, cnt, s + a[u]);
}
int main()
{
	scanf("%d", &T);
	while(T --) {
		scanf("%d", &n);
		res = inf;
		k = n >> 1;
		memset(top, 0, sizeof top);
		for(int i = 0; i < n; i ++) scanf("%d", &a[i]);
		dfs(0, 0, 0);
		for(int i = 0; i <= k; i ++) sort(f[i], f[i] + top[i]);
		dfs2(k, k, 0);
		printf("%lld\n", res);
	}
	return 0;
}
原文