OpenJudge 2795 金银岛

时间:2021-07-27 10:47:39

1.链接地址:

http://bailian.openjudge.cn/practice/2795/

2.题目:

总Time Limit:
3000ms
Memory Limit:
65536kB
Description
某天KID利用飞行器飞到了一个金银岛上,上面有许多珍贵的金属,KID虽然更喜欢各种宝石的艺术品,可是也不拒绝这样珍贵的金属。但是他只带着一个口袋,口袋至多只能装重量为w的物品。岛上金属有s个种类, 每种金属重量不同,分别为n1, n2, ... , ns,同时每个种类的金属总的价值也不同,分别为v1,v2, ..., vs。KID想一次带走价值尽可能多的金属,问他最多能带走价值多少的金属。注意到金属是可以被任意分割的,并且金属的价值和其重量成正比。
Input
第1行是测试数据的组数k,后面跟着k组输入。

每组测试数据占3行,第1行是一个正整数w (1 <= w <= 10000),表示口袋承重上限。第2行是一个正整数s (1 <= s <=100),表示金属种类。第3行有2s个正整数,分别为n1, v1, n2, v2, ... , ns, vs分别为第一种,第二种,...,第s种金属的总重量和总价值(1 <= ni <= 10000, 1 <= vi <= 10000)。

Output
k行,每行输出对应一个输入。输出应精确到小数点后2位。
Sample Input
2
50
4
10 100 50 30 7 34 87 100
10000
5
1 43 43 323 35 45 43 54 87 43
Sample Output
171.93
508.00

3.思路:

贪心问题,主要要注意qsort的时候不能直接相减返回,要注意精度

4.代码:

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath> using namespace std; struct METAL
{
double price;
int total;
int weight;
}; int cmp(const void* a,const void *b)
{
METAL metal_a = *((METAL *)a);
METAL metal_b = *((METAL *)b); if(metal_b.price > metal_a.price) return ;
else if(metal_b.price == metal_b.price) return ;
else return -;
} int main()
{
//freopen("C://input.txt","r",stdin); int i; int k;
cin >> k; while(k--)
{
int w;
int s;
cin >> w >> s; METAL *arr_metal = new METAL[s]; for(i = ; i < s; ++i)
{
cin >> arr_metal[i].weight >> arr_metal[i].total;
arr_metal[i].price = arr_metal[i].total * 1.0 / arr_metal[i].weight;
} qsort(arr_metal,s,sizeof(METAL),cmp); //for(i = 0; i < s; ++i) cout << arr_metal[i].price << " " << arr_metal[i].weight << endl; double sum = 0.0;
for(i = ; i < s; ++i)
{
if(w > arr_metal[i].weight) {sum += arr_metal[i].total;w -= arr_metal[i].weight;}
else {sum += w * arr_metal[i].price; break;}
} cout.setf(ios::fixed);
cout.precision();
cout << sum << endl; delete [] arr_metal;
} return ;
}