帮忙改个背包问题,主要是数据输入不成功
#include<stdio.h>#include<iostream>
#define M 20
typedef struct node{
int weight;
int price;
int flag;
}Node;
typedef struct knap {
Node a[M];
int total;
int size;
}*Knap;
int f(Knap k)
{
int index=-1;
int mp=0;
int i;
for(i=0;i<k->size-1;i++)
{
if((k->a[i].flag==0)&&(k->a[i].price>mp))
{
mp=k->a[i].price;
index=i;
}
}
return index;
}
void PrintResult(Knap k)
{
int i=0;
int total=0;
for(i=0;i<k->size-1;i++)
{
if(k->a[i].flag==1)
{
total+=k->a[i].price;
printf("%d\n",k->a[i].price);
}
}
printf("total= %d\n",total);
}
void select(Knap k,int f(Knap k))
{
int idx;
int count=0;
while((idx=f(k))!=-1)
{
if((count+k->a[idx].weight)<=k->total)
{
k->a[idx].flag=1;
count+=k->a[idx].weight;
k->total-count;
printf("total= %d\n",k->total);
}
else{
k->a[idx].flag=2;
}
}
PrintResult(k);
}
int main()
{
int a[20];
int b[20];
Knap k;
int n,i,m;
printf("你准备对几件物品进行操作:");
scanf("%d",&n);
k->size=n;
printf("请输入你限制的总重量:");
scanf("%d",&m);
k->total=m;
for(i=0;i<n;i++)
{
printf("请输入第%d件物品的价值",i);
scanf("%d",&a[i]);
k->a[i].price=a[i];
}
for(i=0;i<n;i++)
{
printf("请输入第%d件物品的重量",i);
scanf("%d",&b[i]);
k->a[i].weight=b[i];
}
select(k,f);
return 0;
}