PAT 天梯赛 L2-003. 月饼 【贪心】

本文介绍了一道PATest平台上的贪心算法题目,通过分析商品的最大平均单价来实现收益最大化的问题。代码中详细展示了从输入数据到排序计算的过程,并最终输出最大可能的总售价。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

https://www.patest.cn/contests/gplt/L2-003

思路
用贪心思路 最后注意一下 总售价有可能是浮点数

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>

using namespace std;
typedef long long LL;

const double PI  = 3.14159265358979323846264338327;
const double E   = 2.718281828459;
const double eps = 1e-6;

const int MAXN = 0x3f3f3f3f;
const int MINN = 0xc0c0c0c0;
const int maxn = 1e3 + 5;
const int MOD  = 1e9 + 7;

struct Node
{
    double x, y, ave;
}q[maxn];

bool comp(Node x, Node y)
{
    return x.ave > y.ave;
}

int main()
{
    int n, d;
    scanf("%d%d", &n, &d);
    memset(q, 0, sizeof(q));
    for (int i = 0; i < n; i++)
        scanf("%lf", &q[i].x);
    for (int i = 0; i < n; i++)
    {
        scanf("%lf", &q[i].y);
        q[i].ave = q[i].y / q[i].x;
    }   
    sort (q, q + n, comp);
    long double sum = 0.0;
    for (int i = 0; i < n; i++)
    {
        if (d >= q[i].x)
        {
            sum += q[i].y;
            d   -= q[i].x;
        }
        else
        {
            sum += q[i].ave * d;
            break;
        }
    }
    printf("%.2Lf\n", sum);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值