背包问题
时间限制(普通/Java):1000MS/3000MS 运行内存限制:65536KByte
总提交:81 测试通过:71
总提交:81 测试通过:71
描述
给定一个最大载重量为M的卡车和N种食品,有食盐,白糖,大米等。已知第 i 种食品的最多拥有Wi 公斤,其商品价值为Vi元/公斤,编程确定一个装货方案,使得装入卡车中的所有物品总价值最大。
输入
输入只包括一个用例,第一行为两个正实数M,N,分别表示卡车载重量和食品种数,接下来N行,每行两个正实数,分别表示第i食品的重量和价值。
输出
输出一含一个数,即装入卡车的最大价值,要求只保留两位小数。
样例输入
5 3
2 9
3 11
1 5
2 9
3 11
1 5
样例输出
21.33
#include<iostream>
using std::cin;
using std::cout;
using std::endl;
#include<algorithm>
using std::sort;
class Thing{
public:
double weight;
double value;
double value_unit;
void set(void){
cin >> weight >> value;
value_unit = value / weight;
}
};
bool compare_thing(Thing a, Thing b){
return a.value_unit > b.value_unit;
}
int main(void){
Thing* thing;
size_t i, kind;
double current_weight;
double current_value;
while (cin >> current_weight >> kind){
thing = new Thing[kind];
for (i = 0; i != kind; ++i){
thing[i].set();
}
sort(thing, thing + kind, compare_thing);
current_value = 0;
for (i = 0; i != kind; ++i){
if (current_weight <= 0){
break;
}
if (thing[i].weight <= current_weight){
current_weight -= thing[i].weight;
current_value += thing[i].value;
}
else if (thing[i].weight > current_weight){
current_value += thing[i].value_unit * current_weight;
break;
}
}
printf("%.2lf\n", current_value);
delete[] thing;
}
return 0;
}