【发布时间】:2014-12-20 22:03:28
【问题描述】:
我写了一个背包类,我用它来解决背包算法。该课程有效,并且正在使用动态规划算法来解决问题。
我在代码中实现了一些优化,以便我使用线性 O(W) 空间来找到最大值,但是当我尝试找到见证时,我仍然需要 O(nW) 空间来保存布尔值表。
谁能告诉我是否有可能找到最大容量的背包的见证人,空间更小,复杂度为 O(nW),这里 W 是背包容量。
如果您认为代码中可能还有更多优化,也请告诉他们。
class Knapsack{
private:
vector< int > value, weight, answer, DP;
vector< bool > isin;
int capacity;
public:
Knapsack( vector< int > value, vector< int > weight, int capacity, bool needWitness ){
this->value = value;
this->weight = weight;
this->capacity = capacity;
this->answer.clear(); this->isin.clear(); this->DP.clear();
this->DP.resize( capacity + 1, false );
if ( needWitness ){
this->isin.resize( value.size() * (capacity + 1), false );
solveWithWitness();
}
else{
solveWithoutWitness();
}
}
void solveWithoutWitness(){
for ( int i = 0; i < value.size(); i++ ){
for ( int w = capacity; w >= weight[i]; w-- ){
if ( DP[w] < value[i] + DP[w - weight[i]] ){
DP[w] = value[i] + DP[w - weight[i]];
}
}
}
}
void solveWithWitness(){
for ( int i = 0; i < value.size(); i++ ){
for ( int w = capacity; w >= weight[i]; w-- ){
if ( DP[w] < value[i] + DP[w - weight[i]] ){
DP[w] = value[i] + DP[w - weight[i]];
isin[ i*capacity + w ] = true;
}
}
}
int position = value.size()-1;
int w = capacity;
while ( position >= 0 ){
if ( isin[ position*capacity + w ] ){
answer.push_back( position );
w -= weight[position];
}
position--;
}
}
vector< int > getWitness(){
return this->answer;
}
int solution(){
return DP[capacity];
}
};
【问题讨论】:
标签: algorithm dynamic-programming knapsack-problem