上海海洋大学
使用分支限界法求解0-1背包问题。
给定n(n<=10)种物品和一个容量为c的背包。物品i的重量是wi,价值为vi,背包的容量为C(C<=100)。
在装入背包的物品时,对每种物品只有两个选择:装入或不装入。
如何选择装入背包中的物品,使得装入背包中物品的总价值最大?
输入格式:
第1行,输入物品个数n和背包容量c
第2行-n+1行,每个物品的重量和价值
输出格式:
背包能获得的最大价值
输入样例:
在这里给出一组输入。例如:
5 10
2 6
2 3
6 5
5 4
4 6
输出样例:
在这里给出相应的输出。例如:15
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 10
#define MAX_C 100
typedef struct {
int value;
int weight;
} Item;
typedef struct {
int value;
int weight;
int level;
} Node;
int max_value = 0;
void branch_and_bound(int level, int weight, int value, Item items[], int n, int max_weight) {
if (weight > max_weight) {
return;
}
if (level == n) {
if (value > max_value) {
max_value = value;
}
return;
}
branch_and_bound(level + 1, weight + items[level].weight, value + items[level].value, items, n, max_weight);
branch_and_bound(level + 1, weight, value, items, n, max_weight);
}
int main() {
int n, c;
scanf("%d %d", &n, &c);
Item items[MAX_N];
for (int i = 0; i < n; i++) {
scanf("%d %d", &items[i].weight, &items[i].value);
}
branch_and_bound(0, 0, 0, items, n, c);
printf("%d\n", max_value);
return 0;
}