L2-003 月饼

贪心的从单价最高的开始买。注意正数不是正整数!!!

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N = 1e3 + 10;
struct Node 
{
   double price; // 单价
   int id; //属于第几个物品
};
double c[N], w[N]; // 正数不是正整数
vector<Node> arr;
bool cmp(Node &a, Node &b) 
{
    //小数比较不能直接 !=,因为小数有误差,但是这题好像不这样写也可以
    if(fabs(a.price - b.price) > 1e-6) return a.price > b.price;
    return a.id > b.id;
}
int main()
{
    double n, d;
    cin >> n >> d;
    for(int i = 1; i <= n; i ++) cin >> c[i];
    for(int i = 1; i <= n; i ++) cin >> w[i];
    for(int i = 1; i <= n; i ++) 
    {
        double price = w[i] / c[i]; // 计算单价
        arr.push_back({price, i});
    }
    double res = 0;
    sort(arr.begin(), arr.end(), cmp); // 排序
    for(int i = 0; i < arr.size(); i ++)
    {
        double price = arr[i].price;
        int id = arr[i].id;
        res += min(c[id], d) * price;
        d -= min(c[id], d);
        if(d <= 0) break;
    }
    printf("%.2lf", res);
    return 0;
}
相关推荐
政企项目老覃8 小时前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水8 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR8 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵9 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽9 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2089 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民11 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean210311 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil20812 小时前
leetcode 78子集
数据结构·算法·leetcode