01背包问题
01背包的状态转换方程 f[i,j] = Max{ f[i-1,j-Wi]+Pi( j >= Wi ), f[i-1,j] }
f[i,j]表示在前i件物品中选择若干件放在承重为 j 的背包中,可以取得的最大价值。
Pi表示第i件物品的价值。
决策:为了背包中物品总价值最大化,第 i件物品应该放入背包中吗 ?
题目描述:
有编号分别为a,b,c,d,e的五件物品,它们的重量分别是2,2,6,5,4,它们的价值分别是6,3,5,4,6,现在给你个承重为10的背包,如何让背包里装入的物品具有最大的价值总和?
name | weight | value | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
a | 2 | 6 | 0 | 6 | 6 | 9 | 9 | 12 | 12 | 15 | 15 | 15 |
b | 2 | 3 | 0 | 3 | 3 | 6 | 6 | 9 | 9 | 9 | 10 | 11 |
c | 6 | 5 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 6 | 10 | 11 |
d | 5 | 4 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 6 | 10 | 10 |
e | 4 | 6 | 0 | 0 | 0 | 6 | 6 | 6 | 6 | 6 | 6 | 6 |
#include <iostream> #include <vector> #define max(a,b) a>b ? a:b using namespace std; int main() { int capacity; int number; cout<<"输入包的容量和物品的数量"<<endl; cin>>capacity>>number; vector<int> weight(number+1); vector<int> value(number+1); vector<vector<int> > array(number+1,vector<int>(capacity+1,0) ); cout<<"按顺序输入所有重量"<<endl; for (int i = 1; i <= number; ++i) { cin>>weight[i]; } cout<<"按顺序输入所有价值"<<endl; for (int i = 1; i <= number; ++i) { cin>>value[i]; } for (int i = 1; i <= number; ++i) { for (int j = 0; j <= capacity; ++j) { if (j >= weight[i]) array[i][j] = max(array[i-1][j] , array[i-1][j-weight[i]] + value[i]); else array[i][j] = array[i-1][j]; } } cout<<array[number][capacity]<<endl; return 0; }