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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#include <fstream>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
vector<long>
read_file(string_view filename)
{
fstream input{ filename };
return { istream_iterator<long>{ input }, {} };
}
template<typename Process>
void
combination(const vector<long>& values, size_t r, Process process)
{
vector<bool> marker(values.size());
fill(marker.end() - ptrdiff_t(r), marker.end(), true);
vector<long> subset(r);
do {
subset.clear();
for ( size_t i = 0; i != values.size(); ++i ) {
if ( marker[i] ) {
subset.emplace_back(values[i]);
}
}
process(subset);
} while ( std::next_permutation(marker.begin(), marker.end()) );
}
void
solve(const vector<long>& weights, long num)
{
auto totalWeight = accumulate(weights.begin(), weights.end(), 0L);
auto groupWeight = totalWeight / num;
auto min_so_far = numeric_limits<long>::max();
for ( size_t i = 1; i < weights.size(); ++i ) {
combination(weights, i, [&](const vector<long>& subset) {
auto subWeight = accumulate(subset.begin(), subset.end(), 0L);
if ( subWeight == groupWeight ) {
auto product = accumulate(subset.begin(), subset.end(), 1L, multiplies<>());
min_so_far = min(min_so_far, product);
}
});
if ( min_so_far != numeric_limits<long>::max() ) {
cout << min_so_far << endl;
return;
}
}
}
void
part1(const vector<long>& weights)
{
solve(weights, 3);
}
void
part2(const vector<long>& weights)
{
solve(weights, 4);
}
int
main()
{
auto weights = read_file("data/day24.txt");
part1(weights);
part2(weights);
}
|