背包问题《阿里巴巴与四十个大盗》

使用贪心算法:

#include <iostream>
#include<algorithm>
using namespace std;

//宝物的数据结构
struct Treature
{
 double cost;
 double weigth;
 double costproferce;
};
bool cmp(Treature a, Treature b);
//1.宝物的数据输入
//2.宝物的性价比排序
//3.装载——重点
int main()
{
 int datanum;
 double Iweigth;
 cin >> datanum >> Iweigth;
 Treature *ps = new Treature[datanum];
 //1.宝物的数据输入
 for (int i = 0; i < datanum; i++)
 {
  cin >> ps[i].cost >> ps[i].weigth;
  ps[i].costproferce = ps[i].cost / ps[i].weigth;
 }
 //2.宝物的性价比排序
 sort(ps, ps + datanum, cmp);
 for (int i = 0; i < datanum; i++)
 {
  cout << ps[i].weigth << " " << ps[i].cost << " " << ps[i].costproferce << endl;
 }
 //3.装载——重点
 double Cost = 0;
 int num = 0;
 while (num<=datanum)
 {
  if (Iweigth == 0){ break; }
  if (Iweigth < ps[num].weigth)
  {
   cout << ps[num].weigth << endl;
   Cost += Iweigth*ps[num].costproferce;
   Iweigth = 0;
  }
  if (Iweigth>ps[num].weigth)
  {
   cout << ps[num].weigth << endl;
   Iweigth -= ps[num].weigth;
   Cost += ps[num].cost;
  }
  num++;
 }
 cout << Cost<<endl;
 delete[]ps;
 ps = NULL;
 return 0;
}

bool cmp(Treature a, Treature b)
{
 return a.costproferce > b.costproferce;
}

原文地址:https://www.cnblogs.com/damaoranran/p/8601653.html