#pragma once
#include <stdio.h>
int len = 10;
int w[] = { 1,5,7,9, 9, 1,6, 3,8,10 };
int v[] = { 2,7,5,8,11,62,9,10,1,100 };
int tmp[10] ; //缓存选取值, 1:选中, 0:未选中
int result[10] ; //选取结果
int maxWeight = 21; //设定最大重量
int maxValue = 0;
void run(int i, int tw, int tv) {
if (i >= len) return;
//路线1:不选取当前值
tmp[i] = 0;
run(i + 1, tw, tv);
//路线2:选取当前值
tmp[i] = 1;
if (tw + w[i] > maxWeight) //重量超过时结束
return;
if (tv + v[i] > maxValue) { //价值更高时更新数据
maxValue = tv + v[i];
for (int j = 0; j < len; j++) {
result[j] = tmp[j];
}
}
run(i + 1, tw + w[i], tv + v[i]);
}
void bag_main() {
for (int i = 0; i < len; i++) {
tmp[i] = 0;
result[i] = 0;
}
run(0, 0, 0);
for (int i = 0; i < len; i++) {
if(result[i])
printf("i:%d weight:%d value:%d\n",i, w[i], v[i]);
}
}
c语言-背包问题求解
最新推荐文章于 2024-09-08 11:46:43 发布