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;
}
相关推荐
踩坑记录21 小时前
leetcode hot100 easy 101. 对称二叉树 递归 层序遍历 bfs
算法·leetcode·宽度优先
2501_940315261 天前
leetcode182动态口令(将字符的前几个元素放在字符串后面)
算法
老鼠只爱大米1 天前
LeetCode经典算法面试题 #98:验证二叉搜索树(递归法、迭代法等五种实现方案详解)
算法·leetcode·二叉树·递归·二叉搜索树·迭代
疯狂的喵1 天前
C++编译期多态实现
开发语言·c++·算法
scx201310041 天前
20260129LCA总结
算法·深度优先·图论
2301_765703141 天前
C++中的协程编程
开发语言·c++·算法
m0_748708051 天前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习1 天前
【算法——c/c++]
c语言·c++·算法
智码未来学堂1 天前
探秘 C 语言算法之枚举:解锁解题新思路
c语言·数据结构·算法
Halo_tjn1 天前
基于封装的专项 知识点
java·前端·python·算法