DEV Community

Guhan M
Guhan M

Posted on

Meet in the Middle | CSES - Algoritmit ongelmanratkaisussa

https://cses.fi/alon/task/1628

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

using namespace std;

int dp[41][41];
int n;
long long x;
long long arr[41];

vector<long long> getSubsetSum(int l, int r) {
    int len = r - l + 1;
    vector<long long> res;
    for (int i = 0; i < (1 << len); i++) {
        long long sum = 0;
        for (int j = 0; j < len; j++) {
            if (i & (1 << j)) {
                sum += arr[l + j];
            }
        }
        res.push_back(sum);
    }
    return res;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);


    cin >> n >> x;
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    vector<long long> left = getSubsetSum(0, n / 2 - 1);
    vector<long long> right = getSubsetSum(n / 2, n - 1);

    sort(left.begin(), left.end());
    sort(right.begin(), right.end());

    long long ways = 0;
    for (long long i : left) {
        auto lb = lower_bound(right.begin(), right.end(), x - i);
        auto ub = upper_bound(right.begin(), right.end(), x - i);
        ways += ub - lb;
    }
    cout << ways << '\n';
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)