zoukankan      html  css  js  c++  java
  • 背包问题《阿里巴巴与四十个大盗》

    使用贪心算法:

    #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;
    }

  • 相关阅读:
    C#变量初始化
    Mcrosoft中间语言的主要特征
    去除json数据的某些键值对
    ASP.NET MVC 之控制器与视图之间的数据传递
    ASP.NET MVC 路由进阶(之二)--自定义路由约束
    ASP.NET WEB API 初探
    Linux学习三部曲(之三)
    Linux学习三部曲(之二)
    Linux学习三部曲(之一)
    C# 3.0 特性之扩展方法
  • 原文地址:https://www.cnblogs.com/damaoranran/p/8601653.html
Copyright © 2011-2022 走看看