假设有一个能装入总体积为T的背包和n件体积分别为w1,w2...wn的物品,能否从n件物品中挑选若干件恰好装满背包,使w1+w2+w3+...+wn=T,要求找出所有满足上述条件的解。设计一个背包问题的函数,编写一个测试主函数,用数据结构c语言版
时间: 2023-06-01 12:02:26 浏览: 121
#include <stdio.h>
#define N 20
void knapsack(int w[], int n, int T, int x[], int &found);
int main()
{
int w[N], x[N], n, T, i, found = 0;
printf("请输入物品数量n和背包总体积T:\n");
scanf("%d%d", &n, &T);
printf("请输入各物品的体积:\n");
for(i = 1; i <= n; i++)
scanf("%d", &w[i]);
knapsack(w, n, T, x, found);
if(!found)
printf("无解\n");
return 0;
}
void knapsack(int w[], int n, int T, int x[], int &found)
{
int i, j, sum;
if(found)
return;
if(n == 0)
{
sum = 0;
for(i = 1; i <= T; i++)
sum += x[i];
if(sum == T)
{
found = 1;
printf("找到一个解:");
for(i = 1; i <= T; i++)
printf("%d ", x[i]);
printf("\n");
}
return;
}
x[n] = 0;
knapsack(w, n - 1, T, x, found);
if(found)
return;
x[n] = w[n];
knapsack(w, n - 1, T, x, found);
if(found)
return;
}
阅读全文