#include<iostream> #include<cstdio> #include<cstdlib> using namespace std; struct goodinfo { float p; //物品效益 float v; //物品价值 float w; //物品重量 float X; //物品该放的数量 int flag; //物品编号 }; //物品信息结构体 void Insertionsort(goodinfo goods[],int n) { int j,i; for(j=2;j<=n;j++) { goods[0]=goods[j]; i=j-1; while (goods[0].p>goods[i].p) { goods[i+1]=goods[i]; i--; } goods[i+1]=goods[0]; } } //按物品效益,重量比值做升序排列 void bag(goodinfo goods[],float M,int n) { float cu; int i,j; for(i=1;i<=n;i++) goods[i].X=0; cu=M; //背包剩余容量 for(i=1;i<n;i++) { if(goods[i].w>cu)//当该物品重量大与剩余容量跳出 break; goods[i].X=1; cu=cu-goods[i].w;//确定背包新的剩余容量 } if(i<=n) goods[i].X=cu/goods[i].w;//该物品所要放的量 //按物品编号做降序排列 for(j=2;j<=n;j++) { goods[0]=goods[j]; i=j-1; while(goods[0].flag<goods[i].flag) { goods[i+1]=goods[i]; i--; } goods[i+1]=goods[0]; } double sum=0.0; cout<<"最优解为:("; for(i=1;i<=n;i++) { if(i==1) cout<<goods[i].X; else cout<<","<<goods[i].X; if(goods[i].X!=0) sum+=goods[i].X*goods[i].v; } cout<<")"<<endl; cout<<"最优解值为:"<<sum<<endl; } int main() { cout<<"|---------运用贪心法解背包问题---------|"<<endl; cout<<"|--------------------------------------|"<<endl; int i,n; float M; goodinfo *goods; //定义一个指针 cout<<"请输入物品的总数量:"; while(cin>>n) { goods=new struct goodinfo [n+1]; cout<<"请输入背包的最大容量:"; cin>>M; cout<<endl; cout<<"请输入"<<n<<"个背包的重量(空格分割):"<<endl; for(i=1;i<=n;i++) { goods[i].flag=i; cin>>goods[i].w; } cout<<"请输入"<<n<<"个背包的价值(空格分割):"<<endl; for(i=1;i<=n;i++) { cin>>goods[i].v; goods[i].p=goods[i].v/goods[i].w; //得出物品的效益,重量比 } Insertionsort(goods,n); bag(goods,M,n); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。