部分背包问题-贪心法源码

#include
#include
//#include
using namespace std;

float Value[100]={0};
float Weight[100]={0};
struct performance
{
int num;
float ratio;
};

performance p[100]={0,-1};
float select[100]={0};

void bubblesort(int);
float Bag(int,float);
//bool cmp(performance,performance);

int main(int argc,char * argv[])
{
int ObjectNum=0;
float Capacity=0;
cout<<"Please input the number of the objects:"<<endl;
cin>>ObjectNum;
cout<<"Please input the Value and Weight of each object:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
cout<<"Number "<<i<<':'<<endl;
cin>>Value[i]>>Weight[i];
}
cout<<"Please input the capacity:"<<endl;
cin>>Capacity;
cout<<"The result is:"<<endl;
cout<<Bag(ObjectNum,Capacity)<<endl;
cout<<"The Selected array:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
cout<<select[i]<<' ';
}
cout<<endl;
cout<<"The selected objects:"<<endl;
for(int i=1;i<=ObjectNum;i++)
{
if(select[i])
cout<<"No."<<i<<' ';
}
cout<<endl;
system("pause");
return 0;
}


float Bag(int objectnum,float capacity)
{
float w=0,v=0;
for(int i=1;i<=objectnum;i++)
{
p[i].num=i;
p[i].ratio=Value[i]/Weight[i];
}
bubblesort(objectnum);
for(int i=1;i<=objectnum;i++)
{
if((w+Weight[p[i].num])<=capacity)
{
w+= Weight[p[i].num],select[p[i].num]=1;
v+= Value[p[i].num];
}
else
{
v+=Value[i]*(capacity-w)/Weight[p[i].num];
select[p[i].num]=(capacity-w)/Weight[p[i].num];
break;
}
}
return v;
}

void bubblesort(int LEN)
{
performance t;
for (int j=1;j
{
for (int i=1;i<=LEN-j;i++)
{
if (p[i].ratio
{
        t=p[i];
        p[i]=p[i+1];
        p[i+1]=t;
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值