Aleph-w 3.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
backtracking_subset_sum_example.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
40# include <iostream>
41# include <string>
42
43# include <State_Search.H>
44
45namespace
46{
47
48namespace Search = Aleph::Search;
49using Aleph::Array;
50
51struct SubsetSumState
52{
53 size_t index = 0;
54 int sum = 0;
56
57 explicit SubsetSumState(const size_t n = 0)
58 : index(0), sum(0), chosen(n, 0)
59 {
60 // empty
61 }
62};
63
64class SubsetSumDomain
65{
66public:
67 struct Move
68 {
69 bool take = false;
70 };
71
72 using State = SubsetSumState;
73
74 explicit SubsetSumDomain(const Array<int> &values, const int target)
75 : values_(values),
76 suffix_remaining_(values.size() + 1, 0),
77 target_(target)
78 {
79 for (size_t i = values_.size(); i > 0; --i)
80 suffix_remaining_[i - 1] = suffix_remaining_[i] + values_[i - 1];
81 }
82
83 bool is_goal(const State &state) const
84 {
85 return state.sum == target_;
86 }
87
88 bool is_terminal(const State &state) const
89 {
90 return state.index == values_.size();
91 }
92
93 bool should_prune(const State &state, const size_t) const
94 {
95 return state.sum > target_ or state.sum + suffix_remaining_[state.index] < target_;
96 }
97
98 void apply(State &state, const Move &move) const
99 {
100 if (move.take)
101 state.sum += values_[state.index];
102
103 state.chosen[state.index] = move.take ? 1 : 0;
104 ++state.index;
105 }
106
107 void undo(State &state, const Move &move) const
108 {
109 --state.index;
110 if (move.take)
111 state.sum -= values_[state.index];
112
113 state.chosen[state.index] = 0;
114 }
115
116 template <typename Visitor>
117 bool for_each_successor(const State &state, Visitor visit) const
118 {
119 if (state.index >= values_.size())
120 return true;
121
122 if (not visit(Move{true}))
123 return false;
124
125 return visit(Move{false});
126 }
127
128 const Array<int> &values() const noexcept
129 {
130 return values_;
131 }
132
133private:
134 Array<int> values_;
135 Array<int> suffix_remaining_;
136 int target_ = 0;
137};
138
139std::string signature(const SubsetSumState &state)
140{
141 std::string s;
142 for (const auto pick : state.chosen)
143 s.push_back(pick ? '1' : '0');
144 return s;
145}
146
147void print_subset(const Array<int> &values, const SubsetSumState &state)
148{
149 std::cout << "{";
150 bool first = true;
151 for (size_t i = 0; i < values.size(); ++i)
152 if (state.chosen[i])
153 {
154 if (not first)
155 std::cout << ", ";
156 std::cout << values[i];
157 first = false;
158 }
159 std::cout << "}";
160}
161
162} // end namespace
163
164int main()
165{
166 const Array<int> values = {4, 1, 1, 2};
167 constexpr int target = 2;
168
169 SubsetSumDomain domain(values, target);
171 policy.stop_at_first_solution = false;
172
174 Engine engine(domain, policy);
176
177 auto result = engine.search(SubsetSumState(values.size()), collector);
178
179 std::cout << "Subset sum target: " << target << '\n';
180 std::cout << "Solutions found: " << result.stats.solutions_found << '\n';
181 std::cout << "Pruned states: " << result.stats.pruned_by_domain << '\n';
182
183 for (auto it = collector.solutions().get_it(); it.has_curr(); it.next_ne())
184 {
185 const auto &solution = it.get_curr();
186 std::cout << "Choice mask: " << signature(solution.state) << " -> ";
187 print_subset(values, solution.state);
188 std::cout << '\n';
189 }
190
191 return 0;
192}
Umbrella header for the implicit state-space search framework.
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:139
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:351
Recursive depth-first backtracking over an implicit state space.
Collector that stores accepted solutions in an Aleph list.
User-facing facade exported by the umbrella search header.
size_t size(Node *root) noexcept
Divide_Conquer_DP_Result< Cost > divide_and_conquer_partition_dp(const size_t groups, const size_t n, Transition_Cost_Fn transition_cost, const Cost inf=dp_optimization_detail::default_inf< Cost >())
Optimize partition DP using divide-and-conquer optimization.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Exploration controls shared across engines.
bool stop_at_first_solution
Stop when the first goal is found.
static mt19937 engine