主题:有陌生好心的你的帮助 我学习将动力倍增
这是背包问题.我自己写的.可是的不到正确结果.还望赐教.谢谢了!!!!!!!!
源程序这个:
#include<stdio.h>
#include<malloc.h>
typedef struct
{
int *base;
int top;
}SqStack;
//*************************************
void Search(int Volume,int num,int *a,int sum,SqStack *Stack)
{
int sign;
for(sign=Stack->base[Stack->top];Stack->base[sign]<num;Stack->base[sign]++)
{
int i=Stack->base[sign],n; i++;
sum=sum+a[Stack->base[sign]];
if(sum==Volume)
{
for(n=0;n<=Stack->top;n++)
printf("%d ",a[Stack->base[n]]);
printf("\n");
sum=sum-a[Stack->base[sign]];
continue;
}else
if(sum>Volume)
{
sum=sum-a[Stack->base[sign]];
continue;
}
/////////////////////////////////////////
for(;i<num;i++)
{
if(sum+a[i]<Volume)
{
Stack->top++;
Stack->base[Stack->top]=i;
Search(Volume,num,a,sum,Stack);
}else
if(sum+a[i]==Volume)
{
for(n=0;n<=Stack->top;n++)
printf("%d ",a[Stack->base[n]]);
printf("%d\n",a[i]);
}
}
sum=sum-a[Stack->base[sign]];
}
}
//*************************************
void main()
{
int Volume,num,i,*a,sum;
SqStack *Stack;
printf("请输入背包的大小: ");
scanf("%d",&Volume);
printf("\n请输入物品件数: ");
scanf("%d",&num);
printf("\n请输入物品大小: ");
a=(int *)malloc(num*sizeof(int));
for(i=0;i<num;i++)
scanf("%d",&a[i]);
Stack=(SqStack *)malloc(sizeof(SqStack));
Stack->base=(int *)malloc(500*sizeof(int));
Stack->top=-1;
Stack->base[++Stack->top]=0;
sum=0;
Search(Volume,num,a,sum,Stack);
}
比如
输入10
6
1 8 4 3 5 2
应得
1 4 3 2
1 4 5
8 2
3 5 2
源程序这个:
#include<stdio.h>
#include<malloc.h>
typedef struct
{
int *base;
int top;
}SqStack;
//*************************************
void Search(int Volume,int num,int *a,int sum,SqStack *Stack)
{
int sign;
for(sign=Stack->base[Stack->top];Stack->base[sign]<num;Stack->base[sign]++)
{
int i=Stack->base[sign],n; i++;
sum=sum+a[Stack->base[sign]];
if(sum==Volume)
{
for(n=0;n<=Stack->top;n++)
printf("%d ",a[Stack->base[n]]);
printf("\n");
sum=sum-a[Stack->base[sign]];
continue;
}else
if(sum>Volume)
{
sum=sum-a[Stack->base[sign]];
continue;
}
/////////////////////////////////////////
for(;i<num;i++)
{
if(sum+a[i]<Volume)
{
Stack->top++;
Stack->base[Stack->top]=i;
Search(Volume,num,a,sum,Stack);
}else
if(sum+a[i]==Volume)
{
for(n=0;n<=Stack->top;n++)
printf("%d ",a[Stack->base[n]]);
printf("%d\n",a[i]);
}
}
sum=sum-a[Stack->base[sign]];
}
}
//*************************************
void main()
{
int Volume,num,i,*a,sum;
SqStack *Stack;
printf("请输入背包的大小: ");
scanf("%d",&Volume);
printf("\n请输入物品件数: ");
scanf("%d",&num);
printf("\n请输入物品大小: ");
a=(int *)malloc(num*sizeof(int));
for(i=0;i<num;i++)
scanf("%d",&a[i]);
Stack=(SqStack *)malloc(sizeof(SqStack));
Stack->base=(int *)malloc(500*sizeof(int));
Stack->top=-1;
Stack->base[++Stack->top]=0;
sum=0;
Search(Volume,num,a,sum,Stack);
}
比如
输入10
6
1 8 4 3 5 2
应得
1 4 3 2
1 4 5
8 2
3 5 2