您的位置:首页 > 其它

部分背包问题(贪心) HDU1009

2015-12-15 16:47 393 查看
问题描述:有n个物体,第i个物体的重量为wi,价值为vi。在总重量不超过c的情况下让总价值尽量高。每一个物体都可以只取走一部分,价值和重量按比例计算。

分析:要综合考虑价格和重量,所以应该从性价比最高的开始拿,就是单位重量价格最高的,知道刚好到达C为止。

例题:hdu1009

FatMouse' Trade

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 58256    Accepted Submission(s): 19510


[align=left]Problem Description[/align]
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.

The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of
cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.

 

[align=left]Input[/align]
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case
is followed by two -1's. All integers are not greater than 1000.

 

[align=left]Output[/align]
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.

 

[align=left]Sample Input[/align]

5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1

 

[align=left]Sample Output[/align]

13.333
31.500

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1100;

struct treasure1
{
double pi, mi;
};
treasure1 treasure[maxn];

bool cmp (treasure1 a, treasure1 b)
{
return a.pi/a.mi > b.pi/b.mi;
}

int main()
{
int v, n;
while(scanf("%d%d", &v, &n) != EOF && v != -1 && n != -1)
{
double sum = 0;
for(int i = 0; i < n; i++)
{
scanf("%lf%lf", &treasure[i].pi, &treasure[i].mi);
}
sort(treasure, treasure+n, cmp);
for(int i = 0; i < n && v > 0; i++)
{
if(treasure[i].mi <= v)
{
v = v - treasure[i].mi;
sum += treasure[i].pi;
}
else
{
sum += treasure[i].pi/treasure[i].mi * v;
v = 0;
}
}
printf("%.3f\n", sum);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息