CP: Subsets with a given sum

You have n positive numbers. Count the subsets (any choice of numbers, including none) whose sum is exactly T. Two subsets are different if they use different positions, even when the values are equal.

What to build

Count from mask = 0 to (1 << n) - 1. For each mask, add up the numbers whose bit is set, and count the masks whose sum equals T.

Requirements

  • Visit every subset with a bit mask
  • Use long long for sums

Input

The first line has n and T. The second line has n numbers.

Output

The number of subsets with sum T.

Constraints

1 ≤ n ≤ 12. Numbers are from 1 to 10⁹. 1 ≤ T ≤ 10¹⁰.

Example

Input:

4 5
1 2 3 4

Output:

2

Why it works

There are 2ⁿ subsets, one for each mask from 0 to 2ⁿ - 1, and bit i of the mask says whether item i is chosen. With n = 12 that is 4,096 masks of 12 steps each, which is fast.

Examples

Example 1 · Input
4 5
1 2 3 4
Expected output
2
Example 2 · Input
3 100
1 2 3
Expected output
0

Hints

Hint 1

for (int mask = 0; mask < (1 << n); mask++) { long long sum = 0; for (int i = 0; i < n; i++) if ((mask >> i) & 1) sum += a[i]; ... }

Hint 2

Compare sum with T and add 1 to the answer when they are equal.

Hint 3

The empty subset has sum 0, which is never equal to T because T is at least 1.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long T;
    cin >> n >> T;
    vector<long long> a(n);
    for (auto& x : a) cin >> x;
    int answer = 0;
    for (int mask = 0; mask < (1 << n); mask++) {
        long long sum = 0;
        for (int i = 0; i < n; i++)
            if ((mask >> i) & 1) sum += a[i];
        if (sum == T) answer++;
    }
    cout << answer << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Bit tricks and subset masks →