背包问题:从n个物件(每个物件的体积为Wi, i=1, 2, …, n)中选取若干个恰好能够填满体积为T的背包。
用栈实现,非递归解。要求解答出所有的方法!
//这是主函数
#include "stdafx.h"
#include "stack.h"
#define N 20
int W[N]={1,3,2,4,5,6,7,8,9,10};
void main()
{
int T=15;
int n=10,length=n;//length代表所有包的个数,而且不会改变
int i=n;//i是用来测试所有包的变量,随着程序的改变而改变
int ans=0;
SqStack S;
InitStack(S);
while(n>0)
{
for( ;i>0;i--)
{
if(T>=W[i-1])
{
Push(S,i);
T=T-W[i-1];
}
}
if(StackLength(S)==length&&T>0||StackEmpty(S)==1&&ans==0)
{
printf("%d",ans);
printf("该问题无解");
return;
}
if(StackEmpty(S)==1)
return;
if(T==0)