经典问题,物品个数为n,背包重量为v,则时间复杂度为O(nv)。
空间复杂度为O(v)。
不过如果要得到选择的最终结果,则需要把中间结果都记录下来,空间复杂度只能也用O(nv)。
#include <iostream> using namespace std; int max(int a,int b) { return a>=b ? a : b; } int bag_use_one_array ( const int weight[], const int value[], const int item_size, const int bag_weight) { int max_value[bag_weight+1]; for (int i=0; i<=bag_weight; i++) { max_value[i] = 0; } for (int i=0; i<item_size; i++) { for (int w=bag_weight; w>=1; w--) { if (weight[i] <= w) { //max_value[w] = max(max_value[w], max_value[w-weight[i]]+value[i]); if ( max_value[w] >= max_value[w-weight[i]]+value[i]) { } else { max_value[w] = max_value[w-weight[i]]+value[i]; } cout << "item:" << i << ",wight:" << w << ",max_value:" << max_value[w] << endl; } } cout << endl; } cout << "max value is : " << max_value[bag_weight] << endl; cout << endl; return max_value[bag_weight]; } int bag_get_best_choice ( const int weight[], const int value[], const int item_size, const int bag_weight) { int max_value[bag_weight+1][item_size+1]; for (int i=0; i<=bag_weight; i++) { max_value[i][0] = 0; } for (int j=0; j<=item_size; j++) { max_value[0][j] = 0; } for (int i=1; i<=item_size; i++) { for (int w=bag_weight; w>=1; w--) { if (weight[i-1] <= w) { if ( max_value[w][i-1] >= max_value[w-weight[i-1]][i-1]+value[i-1]) { max_value[w][i] = max_value[w][i-1]; } else { max_value[w][i] = max_value[w-weight[i-1]][i-1]+value[i-1]; } } else { max_value[w][i] = max_value[w][i-1]; } cout << "item:" << i << ",wight:" << w << ",max_value:" << max_value[w][i] << endl; } cout << endl; } cout << "max value is : " << max_value[bag_weight][item_size] << endl; cout << endl; int choice[item_size]; int weight_choice = bag_weight; for (int i=item_size-1; i>=0; i--) { if (max_value[weight_choice][i+1] > max_value[weight_choice][i]) { choice[i]=1; weight_choice -= weight[i]; } else { choice[i]=0; } } for (int i=0; i<item_size; i++) { cout << choice[i] << " "; } cout << endl; return max_value[bag_weight][item_size]; } int main() { const int item_size = 5; const int bag_weight = 15; int weight[item_size] = {12,1,4,1,2}; int value[item_size] = {4,2,10,1,2}; //bag_use_one_array(weight, value, item_size, bag_weight); bag_get_best_choice(weight, value, item_size, bag_weight); return 0; }
时间: 2024-10-23 20:28:26