Kai*_*Kid 6 c++ arrays algorithm knapsack-problem multidimensional-array
I have a problem which is similar to the Knapsack problem, more specifically the multidimensional variation.
I have a bunch of objects which all have a cost, a value, and a category. I need to the Knapsack optimisation for value under a maximum cost, but also have a specific number of objects in each category.
I have successfully implemented in C++ the original knapsack algorithm, without paying attention to the categories.
When I tried to add the categories, I figured out that I could simply treat this as a multidimensional knapsack problem, which each categories being a weight of either 0 or 1 in a new dimension.
我的主要问题是,我不仅有一个最大值,例如:5 个食物类型的对象,而且还有一个最小值,因为我正好需要5 个食物类型的对象。
我不知道如何在算法中添加最小值。
显然,我可以使用一般情况,其中每个维度都有最大值和最小值,并对总数进行优化,因为除了一个维度之外,我的所有维度的范围都只有 1,所以无论如何这最终都会针对值进行优化。此外,我可以将值的最小值设置为零,以避免一维没有最小值,并且它仍然有效。
我正在使用 C++ 工作,但老实说,即使是伪代码也可以,我只需要算法。
显然我也需要它快,如果可能的话和多维变化一样快.
这是测试用例的示例。由于这主要是一个优化问题,实例很大,但它应该适用于任何实例大小。可能的类别数量和类别字段数量是固定的。
您有一个最多可容纳 100 个重量单位的背包,以及一个包含 1000 个对象的列表,每个对象都有一个值、一个重量和一个类型。您特别需要携带 10 件食物类型的物品、15 件衣服类型的物品和 5 件工具。每个物体都有一个完全任意的(但大于 0)美元价值和单位重量。我需要找到考虑到最大重量和每种类型物品的具体数量的最佳价值配置。
对象列表将始终包含至少一个有效配置,这意味着它将始终具有至少足够的每种类型的对象,最终将达到最大重量,因此我不必为“无答案”做好计划案件。我只需要为(可能)大量可用项目找到最佳答案。
确切地知道可以从每个类别中选择多少个项目是一个很大的限制。考虑最简单的情况,即只有一个类别。您可以选择恰好 N 个对象来最大化值 sum[v_i x_i],成本 sum[w_i x_i] < W,其中 x_i 等于 0 或 1(遵循维基百科的符号)。新的约束是 sum[x_i] = N。可以通过在动态规划中添加另一个维度来将该约束包含在问题中,但显式检查解是否有效以及是否具有所需元素的数量。
香草背包问题
以下是一个简短的演示:以通过记忆解决标准 0/1 背包问题的解决方案为起点:
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using uint = unsigned int;
template <typename T>
struct item {
T value;
uint weight;
};
template <typename T>
T knapSack(uint W, const std::vector< item<T> >& items) {
std::map< std::pair<uint, uint>, T> cache;
std::function<T(uint, uint)> recursion;
recursion = [&] (uint n, uint w) {
if (n == 0)
return 0;
auto it = cache.find(std::make_pair(n,w));
if (it != cache.end())
return it->second;
T _v = items[n-1].value;
uint _w = items[n-1].weight;
T nextv;
if (_w <= w)
nextv = std::max(_v + recursion(n-1,w-_w),recursion(n-1,w));
else
nextv = recursion(n-1,w);
cache.insert(std::make_pair(std::make_pair(n,w),nextv));
return nextv;
};
return recursion(items.size(),W);
}
Run Code Online (Sandbox Code Playgroud)
我在这里的实现(使用递归 lambda 函数)强调可读性而不是最优性。选择索引 < N 且权重总和 < W 的对象是选择索引 < N-1 且权重总和 < W 的对象,或者选择 N-1 处的对象以及索引 < N-1 且总和的对象权重 < W - w[N-1]。
具有固定所需对象数量的一类的背包问题
我们可以继续添加一个新的限制来跟踪所选元素的数量。我们将通过注意到每个递归步骤中新选择的对象比之前的对象多 0 或 1 个元素来做到这一点,就像它具有相同或更大的权重总和一样 - 即,选择索引 < N 且权重总和 < W 的 K 个对象是索引 < N-1 且权重总和 < W 的 K 个对象的选择,或者是 N-1 处的对象以及索引 < N-1 的 K-1 个对象且权重总和 < W - w[N-1]。然而,我们还想跟踪违规行为——例如,当 K>N 时,我们无法找到索引 < N 的 K 个对象。在这种情况下,我们应该报告最大可能值为 0,因为选择是不可能的,但我们应该将其标记为“无效”,以将其与递归的简单基本情况区分开来。此外,任何试图将其用作子解决方案的链上游解决方案也应标记为无效。因此,我们将返回类型从简单值更改为值和布尔值对。作为基本情况的一部分,我们将所有 K>N 的条目标记为最大值为 0,但无效:
template <typename T>
std::pair<T,bool> knapSackConstrained(uint W, uint K, const std::vector< item<T> >& items) {
std::map< std::tuple<uint, uint, uint>, std::pair<T,bool> > cache;
std::function<std::pair<T, bool>(uint, uint, uint)> recursion;
recursion = [&] (uint n, uint w, uint k) {
if (k > n)
return std::make_pair(0,false);
if (n == 0 || k == 0)
return std::make_pair(0,true);
auto it = cache.find(std::make_tuple(n,w,k));
if (it != cache.end())
return it->second;
T _v = items[n-1].value;
uint _w = items[n-1].weight;
T nextv;
bool nextvalid = true;
if (_w <= w) {
auto take = recursion(n-1,w-_w,k-1);
auto reject = recursion(n-1,w,k);
if (take.second and reject.second) {
nextv = std::max(_v + take.first,reject.first);
} else if (take.second) {
nextv = _v + take.first;
} else if (reject.second) {
nextv = reject.first;
} else {
nextv = 0;
nextvalid = false;
}
} else {
std::tie(nextv,nextvalid) = recursion(n-1,w,k);
}
std::pair<T,bool> p = std::make_pair(nextv,nextvalid);
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
};
return recursion(items.size(),W,K);
}
Run Code Online (Sandbox Code Playgroud)
这是运行此代码及其输出的简单主例程:
int main(int argc, char *argv[]) {
std::vector< item<int> > items = {{60,10},{10,6},{10,6}};
int j = 13;
std::cout << "Unconstrained: " << knapSack(j,items) << std::endl;
for (uint k = 1; k <= items.size(); ++k) {
auto p = knapSackConstrained(j,k,items);
std::cout << "K = " << k << ": " << p.first;
if (p.second)
std::cout << std::endl;
else
std::cout << ", no valid solution" << std::endl;
}
return 0;
}
% OUTPUT %
Unconstrained: 60
K = 1: 60
K = 2: 20
K = 3: 0, no valid solution
Run Code Online (Sandbox Code Playgroud)
由于 3 个权重之和已经大于阈值,因此需要所有三个权重的解决方案是不可能的。
具有固定所需对象数量的多类别背包问题
以上仅部分解决了您的问题,因为您有多个类别,而不仅仅是一个类别。然而,我相信这可以扩展到多维,而不需要太多额外的工作。事实上,我怀疑下面的代码对于多维情况、模错误来说是正确的策略——它需要一些好的测试用例来进行验证。单个参数 K 被替换为类别号向量,并且项目结构被赋予一个类别字段。基本情况必须考虑每种可能的 K>N 情况(对于每个类别),此外,必须扩展对第 (i-1) 个权重小于 W 的检查,以检查是否还需要至少 1 项第 (i-1) 类。
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using uint = unsigned int;
template <typename T>
struct item {
T value;
uint weight;
uint category;
};
template <typename T>
std::pair<T,bool> knapSack(uint W, const std::vector<uint>& K, const std::vector< item<T> >& items) {
std::map< std::tuple<uint, uint, std::vector<uint> >, std::pair<T,bool> > cache;
std::function<std::pair<T, bool>(uint, uint, std::vector<uint>)> recursion;
recursion = [&] (uint n, uint w, std::vector<uint> k) {
auto it = cache.find(std::make_tuple(n,w,k));
if (it != cache.end())
return it->second;
std::vector<uint> ccount(K.size(),0);
for (uint c = 0; c < K.size(); ++c) {
for (uint i = 0; i < n; ++i) {
if (items[i].category == c)
++ccount[c];
}
}
for (uint c = 0; c < k.size(); ++c) {
if (k[c] > ccount[c]) {
auto p = std::make_pair(0,false);
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
}
}
uint sumk = 0; for (const auto& _k : k) sumk += _k;
if (n == 0 || sumk == 0) {
auto p = std::make_pair(0,true);
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
}
T _v = items[n-1].value;
uint _w = items[n-1].weight;
uint _c = items[n-1].category;
T nextv;
bool nextvalid = true;
if (_w <= w and k[_c] > 0) {
std::vector<uint> subk = k;
--subk[_c];
auto take = recursion(n-1,w-_w,subk);
auto reject = recursion(n-1,w,k);
if (take.second and reject.second) {
nextv = std::max(_v + take.first,reject.first);
} else if (take.second) {
nextv = _v + take.first;
} else if (reject.second) {
nextv = reject.first;
} else {
nextv = 0;
nextvalid = false;
}
} else {
std::tie(nextv,nextvalid) = recursion(n-1,w,k);
}
std::pair<T,bool> p = std::make_pair(nextv,nextvalid);
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
};
return recursion(items.size(),W,K);
}
int main(int argc, char *argv[]) {
std::vector< item<int> > items = {{60,10,0}, {100,20,1}, {120,30,0}, {140,35,1}, {145,40,0}, {180,45,1}, {160,50,1}, {170,55,0}};
int j = 145;
for (uint k1 = 0; k1 <= items.size(); ++k1) {
for (uint k2 = 0; k2 <= items.size(); ++k2) {
auto p = knapSack(j,std::vector<uint>({k1,k2}),items);
if (p.second)
std::cout << "K0 = " << k1 << ", K1 = " << k2 << ": " << p.first << std::endl;
}
}
return 0;
}
% OUTPUT (with comments) %
K0 = 0, K1 = 0: 0
K0 = 0, K1 = 1: 180 // e.g. {} from 0, {180} from 1
K0 = 0, K1 = 2: 340 // e.g. {} from 0, {160,180} from 1
K0 = 0, K1 = 3: 480 // e.g. {} from 0, {140,160,180} from 1
K0 = 1, K1 = 0: 170 // e.g. {170} from 0, {} from 1
K0 = 1, K1 = 1: 350 // e.g. {170} from 0, {180} from 1
K0 = 1, K1 = 2: 490 // e.g. {170} from 0, {140, 180} from 1
K0 = 1, K1 = 3: 565 // e.g. {145} from 0, {100, 140, 180} from 1
K0 = 2, K1 = 0: 315 // e.g. {145,170} from 0, {} from 1
K0 = 2, K1 = 1: 495 // e.g. {145,170} from 0, {180} from 1
K0 = 2, K1 = 2: 550 // e.g. {60,170} from 0, {140,180} from 1
K0 = 2, K1 = 3: 600 // e.g. {60,120} from 0, {100,140,180} from 1
K0 = 3, K1 = 0: 435 // e.g. {120,145,170} from 0, {} from 1
K0 = 3, K1 = 1: 535 // e.g. {120,145,170} from 0, {100} from 1
K0 = 3, K1 = 2: 605 // e.g. {60,120,145} from 0, {100,180} from 1
K0 = 4, K1 = 0: 495 // e.g. {60,120,145,170} from 0, {} from 1
Run Code Online (Sandbox Code Playgroud)
对于给定的一组具有两个类别的项目,输出似乎是正确的,尽管我的手动检查可能无法发现一些问题[此答案的早期版本确实有一些错误]。所有未打印的案例都是无解的案例。
返回选定对象的集合
如果您希望函数返回选定对象的集合,原则上这不是障碍 - 代码只会变得更加混乱。最容易理解的事情就是简单地将 an 添加到和 bystd::set<std::size_t>返回的对象元组中,并将其存储在缓存中,表示所选对象的索引集合。每次添加新对象时,该集合都会被扩充。生成的代码涉及大量整数集的复制,并且可能远非最佳——更好的解决方案可能涉及一个静态布尔向量,其条目可以打开和关闭。然而,它有效并且有意义,所以这里是:recursionknapSack
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
using uint = unsigned int;
template <typename T>
struct item {
T value;
uint weight;
uint category;
};
template <typename T>
std::tuple<T,bool,std::set<size_t> > knapSack(uint W, std::vector<uint> K, const std::vector< item<T> >& items) {
std::map< std::tuple<uint, uint, std::vector<uint> >, std::tuple<T,bool,std::set<std::size_t> > > cache;
std::function<std::tuple<T,bool,std::set<std::size_t> >(uint, uint, std::vector<uint>&)> recursion;
recursion = [&] (uint n, uint w, std::vector<uint>& k) {
auto it = cache.find(std::make_tuple(n,w,k));
if (it != cache.end())
return it->second;
std::vector<uint> ccount(K.size(),0);
for (uint i = 0; i < n; ++i) {
++ccount[items[i].category];
}
for (uint c = 0; c < k.size(); ++c) {
if (k[c] > ccount[c]) {
auto p = std::make_tuple(0,false,std::set<std::size_t>{});
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
}
}
uint sumk = 0; for (const auto& _k : k) sumk += _k;
if (n == 0 || sumk == 0) {
auto p = std::make_tuple(0,true,std::set<std::size_t>{});
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
}
T _v = items[n-1].value;
uint _w = items[n-1].weight;
uint _c = items[n-1].category;
T nextv;
bool nextvalid = true;
std::set<std::size_t> nextset;
if (_w <= w and k[_c] > 0) {
--k[_c];
auto take = recursion(n-1,w-_w,k);
++k[_c];
auto reject = recursion(n-1,w,k);
T a = _v + std::get<0>(take);
T b = std::get<0>(reject);
if (std::get<1>(take) and std::get<1>(reject)) {
nextv = std::max(a,b);
if (a > b) {
nextset = std::get<2>(take);
nextset.insert(n-1);
} else {
nextset = std::get<2>(reject);
}
} else if (std::get<1>(take)) {
nextv = a;
nextset = std::get<2>(take);
nextset.insert(n-1);
} else if (std::get<1>(reject)) {
nextv = b;
nextset = std::get<2>(reject);
} else {
nextv = 0;
nextvalid = false;
nextset = {};
}
} else {
std::tie(nextv,nextvalid,nextset) = recursion(n-1,w,k);
}
auto p = std::make_tuple(nextv,nextvalid,nextset);
cache.insert(std::make_pair(std::make_tuple(n,w,k),p));
return p;
};
return recursion(items.size(),W,K);
}
int main(int argc, char *argv[]) {
std::vector< item<int> > items = {{60,10,0}, {100,20,1}, {120,30,0}, {140,35,1}, {145,40,0}, {180,45,1}, {160,50,1}, {170,55,0}};
int j = 145;
for (uint k1 = 0; k1 <= items.size(); ++k1) {
for (uint k2 = 0; k2 <= items.size(); ++k2) {
auto p = knapSack(j,std::vector<uint>({k1,k2}),items);
if (std::get<1>(p)) {
std::cout << "K0 = " << k1 << ", K1 = " << k2 << ": " << std::get<0>(p);
std::cout << "; contents are {";
for (const auto& index : std::get<2>(p))
std::cout << index << ", ";
std::cout << "}" << std::endl;
}
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个的输出是
K0 = 0, K1 = 0: 0; contents are {}
K0 = 0, K1 = 1: 180; contents are {5, }
K0 = 0, K1 = 2: 340; contents are {5, 6, }
K0 = 0, K1 = 3: 480; contents are {3, 5, 6, }
K0 = 1, K1 = 0: 170; contents are {7, }
K0 = 1, K1 = 1: 350; contents are {5, 7, }
K0 = 1, K1 = 2: 490; contents are {3, 5, 7, }
K0 = 1, K1 = 3: 565; contents are {1, 3, 4, 5, }
K0 = 2, K1 = 0: 315; contents are {4, 7, }
K0 = 2, K1 = 1: 495; contents are {4, 5, 7, }
K0 = 2, K1 = 2: 550; contents are {0, 3, 5, 7, }
K0 = 2, K1 = 3: 600; contents are {0, 1, 2, 3, 5, }
K0 = 3, K1 = 0: 435; contents are {2, 4, 7, }
K0 = 3, K1 = 1: 535; contents are {1, 2, 4, 7, }
K0 = 3, K1 = 2: 605; contents are {0, 1, 2, 4, 5, }
K0 = 4, K1 = 0: 495; contents are {0, 2, 4, 7, }
Run Code Online (Sandbox Code Playgroud)
算法复杂度
这不是我的强项,但我相信运行时复杂度是伪多项式的,因为该算法与标准背包算法非常相似。