#include <stdio.h>
#define N 10
#define W 19
int Index[N] = {0};
int Stack[N] = {0};
int MaxWeight = 0;
int CurrentWeight = 0;
int BeiBao(int weights[],int Stack[],int nStart,int nSize,int nCount,int TotalWeight);
int main(int argc, char* argv[])
{
int weight[] = {3,2,4,5,7,8,2,4,3,2};
int Valid = -1;
int i = 0;
for (i=0;i<N;++i)
{
Index[i] = Valid;
}
if (BeiBao(weight,Stack,0,sizeof(weight)/sizeof(int),0,W))
{
printf("find it\n");
}
else
{
printf("can not find it\n");
}
for (i = 0;Index[i]!=-1;++i)
{
printf("%d\t",weight[Index[i]]);
}
return 0;
}
int BeiBao(int weights[],int Stack[],int nStart,int nSize,int nCount,int TotalWeight)
{
int i = 0;
int j = 0;
for (i=nStart;i<nSize;++i)
{
if (MaxWeight+weights[i]<TotalWeight)
{
Stack[nCount++] = i;
if(MaxWeight>CurrentWeight)
{
for (j=0;j<nCount;++j)
{
Index[j] = Stack[j];
}
CurrentWeight = MaxWeight;
printf("%d\n",CurrentWeight);
}
MaxWeight+=weights[i];
if (BeiBao(weights,Stack,i+1,nSize,nCount,TotalWeight))
{
return 1;
}
else
{
MaxWeight -= weights[i];
Stack[--nCount] = -1;
}
}
else if (MaxWeight+weights[i]==TotalWeight)
{
Index[nCount] = i;
return 1;
}
}
return 0;
}
自己实现的递归背包算法
最新推荐文章于 2022-04-29 19:53:22 发布