您的位置:首页 > 其它

回溯法解决0-1背包问题

2015-05-30 21:17 274 查看
1004.0-1背包问题

时限:1000ms 内存限制:10000K 总时限:3000ms

描述

需对容量为c 的背包进行装载。从n 个物品中选取装入背包的物品,每件物品i 的重量为wi ,价值为pi 。对于可行的背包装载,背包中物品的总重量不能超过背包的容量,最佳装载是指所装入的物品价值最高。

输入

多个测例,每个测例的输入占三行。第一行两个整数:n(n<=10)和c,第二行n个整数分别是w1到wn,第三行n个整数分别是p1到pn。

n 和 c 都等于零标志输入结束。

输出

每个测例的输出占一行,输出一个整数,即最佳装载的总价值。

输入样例

1 2

1

1

2 3

2 2

3 4

0 0

输出样例

1

4

#include <iostream>
using namespace std;

int c; //容量
int n;//n个物品
int w[11] = { 0 }; //重量数组
int p[11] = { 0 };//价值数组

int bestValue = 0; //最佳转载
int currentValue = 0, currentW = 0;
void backTack(int i);
void init();
int main() {
while (cin >> n >> c) {
if (n == 0 && c == 0) {
break;
}
for (int i = 1; i <= n; i++) {
cin >> w[i];
}
for (int i = 1; i <= n; i++) {
cin >> p[i];
}
backTack(1);
cout << bestValue << endl;

init();
}

}

void init() {
bestValue = 0; //最佳转载
currentValue = 0;
currentW = 0;
}

void backTack(int i) {
if (i > n) {
if (currentValue >= bestValue) {
bestValue = currentValue;
}
}
else {
if (currentW + w[i] <= c) { //剪枝条件
currentW += w[i];
currentValue += p[i];
backTack(i + 1);
currentValue -= p[i];
currentW -= w[i];
}
//因为currentW + 0 = currentW; currentValue + = currentValue
backTack(i + 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: