首页 > 代码库 > 01背包问题实现源码
01背包问题实现源码
经典问题,物品个数为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; }
本文出自 “天眼神童的新家” 博客,请务必保留此出处http://tianyanshentong.blog.51cto.com/3356396/1556397
01背包问题实现源码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。