问题描述:
给定n种物品和一背包,物品i的重量是wi,其价值为vi,背包的容量为C。问应如何选择装入背包的物品(物品不能分割),使得装入背包中物品的总价值最大? 抽象描述: x[n]:表示物品的选择,x[i]=1表示选择放进物品i到背包中。![](http://www.cppblog.com/images/cppblog_com/geek/QQ.jpg)
![](http://www.cppblog.com/images/cppblog_com/geek/2.jpg)
![](http://www.cppblog.com/images/cppblog_com/geek/3.jpg)
#include#include using namespace std;int maxPrice(int n, int c, vector vecw, vector vecp);int main(){ //物品的数量和背包的容量 int n, c, weight, price; //获得n个物体的重量和价值,n,c都为0的时候结束 cin >> n >> c; while( n != 0 && c != 0 ) { // 物品的重量vecw和物体的价值vecp vector vecw, vecp; for (int i = 0; i < n; ++i) { cin >> weight; vecw.push_back(weight); } for (int j = 0; j < n; ++j) { cin >> price; vecp.push_back(price); } //找到价值的最大值 int max_Price = maxPrice(n, c, vecw, vecp); cout << max_Price << endl; cin >> n >> c; } return 0;}int maxPrice(int n, int c, vector vecw, vector vecp){ int price = 0, flag = 0; if (c == 0) return 0; for(int l = 0; l < n; ++l)//测试是否有能装入包中的数据 if (vecw[l] < c) { flag = 1; break; } if (flag == 0) //如果没有能装入包中的数据就返回 0 return 0; for(int i = 0; i < n; ++i) { int weight = c; weight -= vecw[i]; if (weight >= 0) { vector vec_w, vec_p; for (int j= 0; j < n; ++j) if ( i != j)//创建一个新的数组存储下一组数据 { vec_w.push_back(vecw[j]); vec_p.push_back(vecp[j]); } int current = vecp[i] + maxPrice(n-1, weight, vec_w, vec_p);//递归求最大值 if ( price < current) price = current; } } return price;}
运行结果: