背包问题(贪心算法)

 
#include <iostream>
using namespace std;
#define M 15
typedef struct thing
{
int tag;
int w;
float p;
float arg;
}thing;
void sort(int n,thing thing1[])
{
thing temp2;
for(int i=0;i<n;i++)
{
  for(int j=i+1;j<n;j++)
  {
  
   if(thing1[i].arg>thing1[j].arg)
   {
    temp2=thing1[i];
    thing1[i]=thing1[j];
    thing1[j]=temp2;
   }
  }
}
}
void greedy(int n,thing thing1[])
{
cout<<"装入顺序:";
int temp=M;
for(int i=0;i<n;i++)
  if(temp>0)
  {
   if(temp-thing1[i].w<0)
   {
    cout<<thing1[i].tag<<"   ";
    cout<<"价值:"<<thing1[i].p/temp<<endl;
    temp-=temp;
   }
   else
   {
   cout<<thing1[i].tag<<"   ";
   cout<<"价值:"<<thing1[i].arg<<endl;
   temp-=thing1[i].w;
   }
  }
  else
  {
   break;
  }
}
void main(int argc,char **argv)
{
int n;
cout<<"please input the number of thing value:"<<endl;
cin>>n;
thing *thing1 = new thing[n];
cout<<"please input the value of thing:"<<n<<"个"<<endl;
for(int i=0;i<n;i++)
{
  thing1[i].tag=i+1;
  cout<<"输入重量:";
  cin>>thing1[i].w;
  cout<<"输入价值:";
  cin>>thing1[i].p;
  thing1[i].arg=thing1[i].p/thing1[i].w;
  cout<<endl;
}
sort(n,thing1);
greedy(n,thing1);
/*for(i=0;i<n;i++)
  cout<<thing1[i].arg<<"   ";
cout<<endl;*/
­
­
­
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值