贪心算法--背包问题

题目描述:

给定一个载重量为M的背包,考虑n个物品,其中第i个物品的重量 wi ,价值vi 1in),要求把物品装满背包,且使背包内的物品价值最大。

背包问题: 

有两类背包问题(根据物品是否可以分割),如果物品不可以分割,称为0-1背包问题动态规划;如果物品可以分割,则称为背包问题贪心算法

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <string.h>
using namespace std;
/**背包问题*/
struct bag{
  int weight;
  int value;
  double cost;
  int index;
  double rate;
};
bool cmp(const bag &a,const bag &b){
  return a.cost>b.cost;
}
double GreedySelector(int n, bag a[], double m)
{
   double left=m;
   int i=0;
   double val=0;
   while(i<=n&&a[i].weight<=left){
    left-=a[i].weight;
    val+=a[i].value;
    a[a[i].index].rate=1.0;

    i++;
   }
   if(i<n){
    a[a[i].index].rate=left/(a[i].weight);

    val+=1.0*(a[i].value)*left/(a[i].weight);
   }
   return val;
}

int main()
{
    int n,m;
    cin>>n;
    cin>>m;

        bag a[1000];

        for(int i=1; i<=n; i++)
        {
            cin>>a[i].weight>>a[i].value;
            a[i].index = i;
            a[i].rate=0;
            a[i].cost=1.0*a[i].value/a[i].weight;
        }
        sort(a, a+n+1, cmp);

        cout<<GreedySelector(n, a, m)<<endl;


    return 0;
}
发布了81 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_41499217/article/details/102672001