Skip to content

送礼物 ​

题目描述 ​

作为惩罚,GY 被遣送去帮助某神牛给女生送礼物 (GY:貌似是个好差事)但是在 GY 看到礼物之后,他就不这么认为了。某神牛有 N 个礼物,且异常沉重,但是 GY 的力气也异常的大 (-_-b),他一次可以搬动重量和在 w 以下的任意多个物品。GY 希望一次搬掉尽量重的一些物品,请你告诉他在他的力气范围内一次性能搬动的最大重量是多少。

输入格式 ​

第一行两个整数,分别代表 W 和 N。

以后 N 行,每行一个正整数表示 Gi。

输出格式 ​

仅一个整数,表示 GY 在他的力气范围内一次性能搬动的最大重量。

样例 #1 ​

样例输入 #1 ​

20 5
7
5
4
18
1

样例输出 #1 ​

19

提示 ​

对于所有测试数据,1≤N≤46, 1≤W,G[i]≤231−1。

题解 ​

双向dfs+二分

先搜前一半,把前一半能拼凑出的所有重量值存放到w数组中,并对数组排序、去重

然后接着进行第二次搜索,把后一半礼物能拼凑出的每个重量值s,在第一次得到的w数组中二分查找,找出小于m-s的数值中最大的一个(也就是第一个大于等于m-s的值的前一个值),用二者的和更新答案

多开一个辅助数组w,用空间换时间

code ​

c++
//
// Created by 黄书恒1 on 2024/10/9.
//
#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<cmath>
#include<set>
#include<map>
#include<unordered_set>

using namespace std;
#define ll long long
#define ull unsigned long long
#define endl '\n'
const int N = 1e5 + 5;
const int mod = 1e9 + 7;
const ll inf = 1e18;
//int d[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};//  上右下左

void solve() {
    int n, m;
    cin >> m >> n;
    vector<ll> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    sort(a.begin(), a.end(), greater<int>()); //从大到小搜 优化搜索顺序
    vector<ll> w(1 << 23);
    int cnt = 0;
    auto dfs1 = [&](auto &dfs1, int u, int s) {
        if (u == n / 2) {
            //先拿前一半 边界
            w[cnt++] = s; //存下当前重量
            return;
        }
        dfs1(dfs1, u + 1, s); //当前不选
        if (s + a[u] <= m) {
            //拿得下就接着拿
            dfs1(dfs1, u + 1, s + a[u]);
        }
    };
    dfs1(dfs1, 0, 0);
    sort(w.begin(), w.begin() + cnt);
    cnt = unique(w.begin(), w.begin() + cnt) - w.begin();
    ll ans = 0;
    auto dfs2 = [&](auto &dfs2, int u, int s) {
        if (u == n) {
            ans = max(ans, *(upper_bound(w.begin(), w.begin() + cnt, m - s) - 1) + s);
            return;
        }
        dfs2(dfs2, u + 1, s);
        if (a[u] + s <= m) {
            dfs2(dfs2, u + 1, s + a[u]);
        }
    };
    dfs2(dfs2, n / 2, 0);
    cout << ans;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    int _ = 1;

    //cin >> _;
    while (_--) {
        solve();
    }
    return 0;
}