若爱若宠txt下载久久:我想要一个背包问题的源程序,能提供给我吗?

来源:百度文库 编辑:查人人中国名人网 时间:2024/04/30 01:47:44
只要是背包问题的程序,能运行出来就可以了

这是动态规划的一个算法
背包问题可以用多种算法解决,回朔算法相当于穷举列出所有可能再选出最佳的,贪心算法则需要多个贪心规则再加上递归筛选才可以使用否则无法得到最优解,模拟退火算法可以解决这个问题,如果需要我也可以给个程序
下面程序默认重量为整数……
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 8 // 背包重量
#define N 5 // 物品个数
#define MIN 1 // 最小重量
struct body {
char name[20];
int size;
int price;
};
typedef struct body object;
int main(void) {
int item[LIMIT+1] = {0};
int value[LIMIT+1] = {0};
int newvalue, i, s, p;
object a[] = {{"物品名",重量,价值},……}};
for(i = 0; i < N; i++) {
for(s = a[i].size; s <= LIMIT; s++){
p = s - a[i].size;
newvalue = value[p] + a[i].price;
if(newvalue > value[s]) {
value[s] = newvalue;
item[s] = i;
}
}
}
printf("物品\t价格\n");
for(i = LIMIT; i >= MIN; i = i - a[item[i]].size) {
printf("%s\t%d\n",a[item[i]].name, a[item[i]].price);
}
printf("合计\t%d\n", value[LIMIT]);
return 0;
}