题解:P3878 [TJOI2010] 分金币

· · 题解

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

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

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

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

已过 Hack,而且仅用 106ms

:::info[\large{\mathbf{Code}}]{open}

#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;
}

:::