CH2401 送礼物[双向搜索]

· · 个人记录

直接暴力枚举复杂度过高,可以折半进行搜索。

具体来说,先搜索前一半可以组合出的不超过W的重量,再搜索后一半可以组合出的不超过W的重量w_i再用二分查找,在第一次搜索得出的重量中找到不超过W - w_i的最大重量,与w_i一起更新答案。

按重量降序排序会减少分支,第二次搜索还需要二分查找,可适当调小后半段的大小。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 50;
int w, n, a[N], ans;
vector<int> v;

void dfs1(int i, int now) {
    if(!i) {
        v.push_back(now);
        return ;
    }
    dfs1(i - 1, now);
    if(1ll * now + a[i] <= w) dfs1(i - 1, now + a[i]); 
}

void dfs2(int i, int now) {
    if(i == n + 1) {
        int x = *(upper_bound(v.begin(), v.end(), w - now) - 1);
        ans = max(ans, x + now);
        return ;
    }       
    dfs2(i + 1, now);
    if(1ll * now + a[i] <= w) dfs2(i + 1, now + a[i]);
}

int main() {
    cin >> w >> n;
    for(int i = 1; i <= n; i++) cin >> a[i];
    sort(a + 1, a + n + 1);
    reverse(a + 1, a + n + 1);
    int d = n / 2 + 2;
    dfs1(d, 0);
    sort(v.begin(), v.end());
    unique(v.begin(), v.end());
    dfs2(d + 1, 0);
    cout << ans << endl;
    return 0;
}