aboutsummaryrefslogtreecommitdiff
path: root/10_advanced_techniques/meet_in_the_middle_1628.cpp
diff options
context:
space:
mode:
Diffstat (limited to '10_advanced_techniques/meet_in_the_middle_1628.cpp')
-rw-r--r--10_advanced_techniques/meet_in_the_middle_1628.cpp42
1 files changed, 42 insertions, 0 deletions
diff --git a/10_advanced_techniques/meet_in_the_middle_1628.cpp b/10_advanced_techniques/meet_in_the_middle_1628.cpp
new file mode 100644
index 0000000..a38c5d4
--- /dev/null
+++ b/10_advanced_techniques/meet_in_the_middle_1628.cpp
@@ -0,0 +1,42 @@
1#include <algorithm>
2#include <iostream>
3#include <numeric>
4#include <unordered_map>
5#include <vector>
6
7void add_to_map(size_t i, size_t e, long long s,
8 const std::vector<long long>& a,
9 std::unordered_map<long long, long long>& m) {
10 if (i == e) { m[s]++; return; }
11 add_to_map(i+1, e, s, a, m);
12 add_to_map(i+1, e, s+a[i], a, m);
13}
14
15long long f(size_t i, size_t e, long long t, long long s,
16 const std::vector<long long>& a,
17 const std::unordered_map<long long, long long>& m) {
18 if (t < 0 || t > s) return 0;
19 if (i == e) return m.find(t) == m.end() ? 0 : m.at(t);
20 return f(i+1, e, t, s-a[i], a, m) + f(i+1, e, t-a[i], s-a[i], a, m);
21}
22
23int main() {
24 size_t n, p;
25 long long x, s{0};
26 std::cin >> n >> x;
27 std::vector<long long> a(n);
28 for (size_t i = 0; i < n; i++)
29 std::cin >> a[i];
30
31 std::sort(a.begin(), a.end(), std::greater<long long>());
32 s = std::accumulate(a.begin(), a.end(), 0LL);
33 if (x > s) {
34 std::cout << "0\n";
35 return 0;
36 }
37
38 p = a.size()/2;
39 std::unordered_map<long long, long long> m;
40 add_to_map(p, a.size(), 0, a, m);
41 std::cout << f(0, p, x, s, a, m) << "\n";
42}

Generated with cgit - Back to sebastiano.tronto.net