在这个问题中,物品是可以分割开的
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
#define NUM 100
using namespace std;
struct good{
int w; // 物品重量
int v; // 物品价值
double c; // 性价比
}a[1001]; // 放物品的数组
// 降序排序
bool cmp(good a, good b){
if(a.c > b.c) return true;
return false;
}
double knapsack(int n, good a[], double c) { // 物品数量n, 物品数组a, 背包容量c
double cleft = c; // 背包剩余容量
int i = 0;
double get_value = 0; // 获得的价值
// 当背包还能装物品时
while(i < n && a[i].w < cleft){
cleft -= a[i].w;
get_value += a[i].v;
i++;
}
// 装满剩下的背包
if(i < n)
get_value += 1 * a[i].v * cleft / a[i].w;
return get_value;
}
int main(){
// 物品数据
int goods_data[][2] = {
{60, 10},
{100, 20},
{120, 30}
} ;
int n = 3;
for(int i = 0;i < n;i++){
a[i].v = goods_data[i][0];
a[i].w = goods_data[i][1];
a[i].c = a[i].v / a[i].w;
}
sort(a, a+n, cmp);
cout << knapsack(n, a, 50);
}