Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/algorithms/dynamic_programming_bellman.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ DynamicProgrammingBellmanWordRamOutput subsetsumsolver::dynamic_programming_bell
}

Weight optimal_value = 0;
for (Weight word = capacity_number_of_words; optimal_value == 0; --word) {
for (Weight word = capacity_number_of_words;
word >= 0 && optimal_value == 0;
--word) {
if (output.values[word] == 0)
continue;
for (int bit = 63; bit >= 0; --bit) {
Expand Down
17 changes: 17 additions & 0 deletions test/algorithms/dynamic_programming_bellman_test.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "subsetsumsolver/tests.hpp"

#include "subsetsumsolver/algorithms/dynamic_programming_bellman.hpp"
#include "subsetsumsolver/instance_builder.hpp"

using namespace subsetsumsolver;

Expand Down Expand Up @@ -100,3 +101,19 @@ INSTANTIATE_TEST_SUITE_P(
get_pthree_instance_paths(1000),
get_psix_instance_paths(10),
})));

TEST(SubsetSumDynamicProgrammingBellmanWordRam, NothingButZeroReachable)
{
// Only weight '0' is reachable: the final scan for the optimal value
// must stop at word '0' instead of reading out of bounds.
for (Weight item_weight: {-1, 200}) {
InstanceBuilder instance_builder;
instance_builder.set_capacity(100);
if (item_weight >= 0)
instance_builder.add_item(item_weight);
const Instance instance = instance_builder.build();
auto output = dynamic_programming_bellman_word_ram(instance);
EXPECT_EQ(output.value, 0);
EXPECT_EQ(output.bound, 0);
}
}
Loading