例1: 有n件物品,每件物品的重量为w[i],价值为c[i]。现在需要选出若干件物品放入一个容量为V的背包中,使得在选入背包的物品重量和不超过容量V的前提下,让背包中物品的价值之和最大,求最大价值。
输入数据:
5 8
3 5 1 2 2
4 5 2 1 3
输出结果:
10
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 30;
int n, V, maxValue = 0;
int w[maxn], c[maxn];
void DFS(int index, int sumW, int sumC){
if(index == n)
{
if(sumW <= V && sumC > maxValue)
maxValue = sumC;
return;
}
DFS(index + 1, sumW, sumC);
DFS(index + 1, sumW + w[index], sumC + c[index]);
}
int main(){
cin >> n >> V;
for(int i = 0; i < n; i++)
cin >> w[i];
for(int i = 0; i < n; i++)
cin >> c[i];
DFS(0, 0, 0);
cout << maxValue;
return 0;
}
剪枝
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 30;
int n, V, maxValue = 0;
int w[maxn], c[maxn];
void DFS(int index, int sumW, int sumC){
if(index == n)
return;
DFS(index + 1, sumW, sumC);
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(){
cin >> n >> V;
for(int i = 0; i < n; i++)
cin >> w[i];
for(int i = 0; i < n; i++)
cin >> c[i];
DFS(0, 0, 0);
cout << maxValue;
return 0;
}
版权声明:本文为jiangjiangjiang6原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。