枚举前半子集存哈希表,枚举后半子集查哈希表

此做法可过n\le 40

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;

int n;
int k;
vector<int> a;

unordered_map<int, int> cnt;
int res;

void Dfs1(int x, int cur) {
    if (cur <= k) {
        cnt[cur]++;
        for (int i = x; i < n / 2; i++) {
            Dfs1(i + 1, cur + a[i]);
        }
    }
}

void Dfs2(int x, int cur) {
    if (cur <= k) {
        res += cnt[k - cur];
        for (int i = x; i < n; i++) {
            Dfs2(i + 1, cur + a[i]);
        }
    }
}

void Solve() {
    cin >> n >> k;
    a.resize(n);
    for (auto& x : a) {
        cin >> x;
    }
    cnt.clear();
    Dfs1(0, 0);
    res = 0;
    Dfs2(n / 2, 0);
    cout << res;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    Solve();
    return 0;
}
// 64 位输出请用 printf("%lld")