背包问题程序(打印不出结果?求大神指教)程序附下!
#include"stdio.h"voidmain(){intw[20]={0};//w[20]用来存放每一个物体的体积ints[20]={0};//s[20]为收入物体...
#include "stdio.h"
void main()
{
int w[20]={0}; //w[20]用来存放每一个物体的体积
int s[20]={0}; //s[20]为收入物体序号的栈
int t; //t为背包能容纳的体积
int i=1; //i为物体的序号
int top=0; //top为栈中元素的个数
int n; //n为现有的物品的个数
int k; //普通计数变量
printf("how many things do you have to put in the bag?\n");
scanf("%d",&n);
printf("please input the Volume of each thing:\n");
for(k=1;k<=n;k++)
scanf("%d",&w[k]);
printf("and how large is the bag?\n");
scanf("%d",&t);
do
{
if((t-w[i]==0)||(t-w[i]>=0&&i<=n))
{top=top+1;s[top]=i;t=t-w[i];}
if(t==0)
{
printf("one of the answer is:\n");
for(k=1;k<=top;k++)
printf("%d,",w[s[k]]);
}
else
{
if(i=n&&top>0)
{
i=s[top];
top=top-1,t=t+w[i];
}
i=i+1;
}
}while(i<=n&&t>0);
} 展开
void main()
{
int w[20]={0}; //w[20]用来存放每一个物体的体积
int s[20]={0}; //s[20]为收入物体序号的栈
int t; //t为背包能容纳的体积
int i=1; //i为物体的序号
int top=0; //top为栈中元素的个数
int n; //n为现有的物品的个数
int k; //普通计数变量
printf("how many things do you have to put in the bag?\n");
scanf("%d",&n);
printf("please input the Volume of each thing:\n");
for(k=1;k<=n;k++)
scanf("%d",&w[k]);
printf("and how large is the bag?\n");
scanf("%d",&t);
do
{
if((t-w[i]==0)||(t-w[i]>=0&&i<=n))
{top=top+1;s[top]=i;t=t-w[i];}
if(t==0)
{
printf("one of the answer is:\n");
for(k=1;k<=top;k++)
printf("%d,",w[s[k]]);
}
else
{
if(i=n&&top>0)
{
i=s[top];
top=top-1,t=t+w[i];
}
i=i+1;
}
}while(i<=n&&t>0);
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询