可分割的背包问题
即挑选单位价值最大的物品装入即可。
宝物 i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
重量w[i] | 4 | 2 | 9 | 5 | 5 | 8 | 5 | 4 | 5 | 5 |
价值v[i] | 3 | 8 | 18 | 6 | 8 | 20 | 5 | 6 | 7 | 15 |
#include <iostream>
#include <algorithm>
using namespace std;
//需要一个结构体,通过性价比,能够查找到重量和价值。
//做一个排序,需要将性价比由高到底排序,排序的过程中重量和(价值)要对应上
typedef struct {
double w;
double v;
double p;
int num;//货物编号,从1开始
}three;
//如果需要记录顺序,可以将开始的顺序记录下来
int main()
{
three s[10];
freopen("D:/project/algorithm/data.csv","r",stdin);
for (int i = 0; i < 10; i++)
{
cin >> s[i].w;
s[i].num = i + 1;
}
for (int i = 0; i < 10; i++)
cin >> s[i].v;
//求性价比
for (int i=0;i<10;i++)
{
s[i].p=s[i].v / s[i].w;
}
for(int i=0;i<10;i++)
for (int j=i+1;j<=10;j++)
{
if (s[i].p<s[j].p)
{
three temp;
temp=s[i];
s[i] = s[j];
s[j] = temp;
}
}
//应该由性价比的顺序,通过容量,选择装入的物品。(此种方式是最直观,最通用的)
for (int i = 0; i < 10; i++)
cout << s[i].p << " ";
int m = 30; double V=0;
for (int i = 0; i < 10;i++) {
if (s[i].w < m)
{
V = V + s[i].p*s[i].w;
m = m - s[i].w;
}
else {//直接将剩余的m加入即可
V=V+m*s[i].p;
m = 0;
}
if (m == 0)
break;
}
cout << endl << V << endl;
return 0;
}