【OpenJ_Bailian - 2795】金银岛(贪心)

金银岛

Descriptions:

某天KID利用飞行器飞到了一个金银岛上,上面有许多珍贵的金属,KID虽然更喜欢各种宝石的艺术品,可是也不拒绝这样珍贵的金属。但是他只带着一个口袋,口袋至多只能装重量为w的物品。岛上金属有s个种类, 每种金属重量不同,分别为n 1, n 2, ... , n s,同时每个种类的金属总的价值也不同,分别为v 1,v 2, ..., v s。KID想一次带走价值尽可能多的金属,问他最多能带走价值多少的金属。注意到金属是可以被任意分割的,并且金属的价值和其重量成正比。

Input

第1行是测试数据的组数k,后面跟着k组输入。 

每组测试数据占3行,第1行是一个正整数w (1 <= w <= 10000),表示口袋承重上限。第2行是一个正整数s (1 <= s <=100),表示金属种类。第3行有2s个正整数,分别为n 1, v 1, n 2, v 2, ... , n s, v s分别为第一种,第二种,...,第s种金属的总重量和总价值(1 <= n i <= 10000, 1 <= v i <= 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

题目链接:

https://vjudge.net/problem/OpenJ_Bailian-2795

这题简直就是OpenJ_Bailian - 4110的变形,一模一样的好吗

链接:https://www.cnblogs.com/sky-stars/p/11073133.html

没啥说的,直接上代码

AC代码

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define ME0(x) memset(x,0,sizeof(x))
using namespace std;
struct gift{
    double v,w;
    //定义按照v/w的大小进行排序,v/w大的优先,即礼物的平均价值大的优先
    bool operator < (const gift &c) const
    {
        return v/w-c.v/c.w > eps;
    }
};
gift a[105];
int n;
double W;
double sum=0;
int main()
{
    cin>>n>>W;
    for(int i=0; i<n; i++)//输入
        cin>>a[i].v>>a[i].w;
    sort(a,a+n);//排序
    for(int i=0; i<n; i++)
    {
        if(W>=a[i].w)
        {
            sum+=a[i].v;
            W-=a[i].w;
        }
        else if(W<a[i].w)
        {
            double t=(a[i].v/a[i].w)*W;
            sum+=t;
            W=0;
        }
        else if(W==0)
        {
            break;
        }
    }
    printf("%.1lf\n",sum);
}

 

posted on 2019-06-23 16:13  Sky丨Star  阅读(506)  评论(0编辑  收藏  举报

导航