背包问题(贪心算法)

来源:互联网 发布:c 网络验证 编辑:程序博客网 时间:2024/04/29 16:17
 
#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;*/
­
­
­
}
原创粉丝点击