#include<stdio.h>
#define N 5
#define limit 10
#define true 1
#define false 0
typedef enum{true_,false_} bool;
typedef struct
{
int weight;
int value;
} item;
typedef struct
{
bool solution[N];
int value;
int weight;
} resault;
item items[N] = {{6,5},{5,3},{4,5},{2,3},{1,6}};
void findOptimum(resault test, int floor, resault* optimum)
{
int i;
int restValue = 0;
if(floor >= N)
{
if(test.value > optimum->value) *optimum = test;
}
else
{
if(test.weight + items[floor].weight <= limit)
{
test.solution[floor] = true;
test.value += items[floor].value;
test.weight += items[floor].weight;
findOptimum(test, floor+1, optimum);
test.solution[floor] = false;
test.value -= items[floor].value;
test.weight -= items[floor].weight;
}
for(i=floor+1; i<N; i++)
{
restValue += items[i].value;
}
if(optimum->value < test.value + restValue)
{
findOptimum(test, floor+1, optimum);
}
}
}
void showResault(resault* test)
{
int i;
printf("\n----------------------\n");
printf("最优解:\n----------------------\n");
printf("物品\t重量\t价值\n");
for(i=0; i<N; i++)
{
if((test->solution)[i])
printf("%d\t%dkg\t%d美元\n", i+1, items[i].weight, items[i].value);
}
printf("----------------------\n");
printf("总量:\t%dkg\t%d美元\n", test->weight, test->value);
printf("----------------------\n");
printf("\n----------------------\n");
printf("全部物品:\n----------------------\n");
printf("物品\t重量\t价值\n");
for(i=0; i<N; i++)
{
printf("%d\t%dkg\t%d美元\n", i+1, items[i].weight, items[i].value);
}
printf("----------------------\n");
printf("背包容量:%dkg\n", limit);
printf("----------------------\n");
}
int main()
{
resault test = {{0},0, 0};
int floor = 0;
findOptimum(test, floor, &test);
showResault(&test);
return 0;
}