标签:
题目描述:
有编号分别为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; }
标签:
原文地址:http://www.cnblogs.com/kbe317/p/4817668.html