蓝桥杯 ADV-167 算法提高 快乐司机

算法提高 快乐司机

时间限制:1.0s   内存限制:256.0MB

 

问题描述

  "嘟嘟嘟嘟嘟嘟
  喇叭响
  我是汽车小司机
  我是小司机
  我为祖国运输忙
  运输忙"
  这是儿歌“快乐的小司机”。话说现在当司机光有红心不行,还要多拉快跑。多拉不是超载,是要让所载货物价值最大,特别是在当前油价日新月异的时候。司机所拉货物为散货,如大米、面粉、沙石、泥土......
  现在知道了汽车核载重量为w,可供选择的物品的数量n。每个物品的重量为gi,价值为pi。求汽车可装载的最大价值。(n<10000,w<10000,0<gi<=100,0<=pi<=100)

 

输入格式

  输入第一行为由空格分开的两个整数n w
  第二行到第n+1行,每行有两个整数,由空格分开,分别表示gi和pi

 

输出格式

  最大价值(保留一位小数)

 

样例输入

5 36
99 87
68 36
79 43
75 94
7 35

 

样例输出

71.3
解释:
先装第5号物品,得价值35,占用重量7
再装第4号物品,得价值36.346,占用重量29
最后保留一位小数,得71.3

 

#include <stdio.h>
#include <stdlib.h>

struct Goods
{
    int g;
    int p;
    double per;
};

int cmp(const void *a, const void *b)
{
    struct Goods *pa = (struct Goods *)a;
    struct Goods *pb = (struct Goods *)b;
    if (pa->per > pb->per)
        return -1;
    else
        return 1;
}

int main()
{
    int n, w;
    struct Goods items[10005];

    scanf("%d %d", &n, &w);
    for (int i = 0; i < n; ++i)
    {
        scanf("%d %d", &items[i].g, &items[i].p);
        items[i].per = (double)items[i].p / items[i].g;
    }

    qsort(items, n, sizeof(struct Goods), cmp);

    double total_price = 0, current_load = 0;
    for (int i = 0; i < n && current_load < w; ++i)
    {
        if (current_load + items[i].g <= w)
        {
            current_load += items[i].g;
            total_price += items[i].p;
        }
        else
        {
            total_price += items[i].per * (w - current_load);
            current_load += (w - current_load);
        }
    }
    printf("%.1lf", total_price);

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值