有n件物品,每件物品的重量为w[i],价值为c[i]。现在需要选出若干件物品放入一个容器为V的背包,使得在选入背包的物品重量和不超过容量V的前提下,让背包中的物品价值之和最大,求最大价值。(1<=n<=20)
样例输入:
5 8
3 5 1 2 2
4 5 2 1 3
样例输出:
10
代码(C/C++):
DFS版:
//DFS版
#include<bits/stdc++.h>
using namespace std;
const int maxn = 30;
int n, V, maxValue = 0; //物品总件数n,背包容量V,最大价值maxValue
int w[maxn], c[maxn]; //每件物品的重量为w[i],价值为c[i]
void DFS(int index, int sumW, int sumC){
if(index == n){
return;
}
DFS(index + 1, sumW, sumC); //不选第index件物品
//只有第index件物品未超过容量V,才继续
if(sumW + w[index] <= V){
if(sumC + c[index] > maxValue){
maxValue = sumC + c[index];
}
DFS(index + 1, sumW + w[index], sumC + c[index]);
}
}
int main(){
scanf("%d%d",&n,&V);
for(int i = 0; i < n; i++){
scanf("%d",&w[i]);
}
for(int i = 0; i < n; i++){
scanf("%d",&c[i]);
}
DFS(0,0,0);
printf("%d",maxValue);
return 0;
}
动态规划版:
//动态规划版
#include<bits/stdc++.h>
using namespace std;
const int maxn = 30;
int n, V, maxValue = 0; //物品总件数n,背包容量V,最大价值maxValue
int w[maxn], c[maxn]; //每件物品的重量为w[i],价值为c[i]
int dp[maxn + 1][maxn + 1];
//从第i个物品开始挑选总重小于j的部分
int rec(int i, int j){
if(dp[i][j] > 0){
return dp[i][j];
}
int res;
if(i == n){
res = 0;
}
else if(j < w[i]){
res = rec(i + 1, j);
}
else{
res = max(rec(i + 1, j), rec(i + 1, j - w[i]) + c[i]);
}
return dp[i][j] = res;
}
int main(){
scanf("%d%d",&n,&V);
memset(dp, -1, sizeof(dp));
for(int i = 0; i < n; i++){
scanf("%d",&w[i]);
}
for(int i = 0; i < n; i++){
scanf("%d",&c[i]);
}
printf("%d\n",rec(0,V));
return 0;
}