-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsetSum.h
More file actions
34 lines (30 loc) · 730 Bytes
/
SubsetSum.h
File metadata and controls
34 lines (30 loc) · 730 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#pragma once
#include <vector>
#include <bitset>
#include <tuple>
// Choose N sufficiently large such that N >= sum + 1
// Might be implemented using a dynamic bitset
template<int N>
bool subsetSum(const std::vector<int>& objs, int sum) {
std::bitset<N> bs(1);
for (int v : objs)
bs |= (bs << v);
return bs[sum];
}
struct SubsetObjects {
int v; // Value
int m; // Multiplicity
};
// Choose N sufficiently large such that N >= sum + 1
template<int N>
bool multiplicitySubsetSum(const std::vector<SubsetObjects>& objs, int sum) {
std::bitset<N> bs(1);
for (auto obj : objs) {
for (int x = 1; x <= obj.m; x *= 2) {
bs |= (bs << (obj.v * x));
obj.m -= x;
}
bs |= (bs << (obj.v * obj.m));
}
return bs[sum];
}