算法竞赛进阶指南0x07 贪心

算法竞赛进阶指南0x07 贪心

P2240 【深基12.例1】部分背包问题

        因为我们可以随意分割金币,所以我们以每堆金币的平均价值为关键字排序,尽可能多地选单位价值最大的金币。

参考代码:

#include <bits/stdc++.h>
#define i64 long long
#define lowbit(x) (x & (-x))
typedef unsigned long long ll;
const int MOD = 1e9 + 7;


template <typename _T>
inline void read(_T &f) {
    f = 0; _T fu = 1; char c = getchar();
    while (c < '0' || c > '9') { if (c == '-') { fu = -1; } c = getchar(); }
    while (c >= '0' && c <= '9') { f = (f << 3) + (f << 1) + (c & 15); c = getchar(); }
    f *= fu;
}

struct node {
    int m, v;
    double value;
};

bool cmp(node x, node y) {
    return x.value > y.value;
}

int main() {
    
    int n, t;
    read(n), read(t);
    // t : 容量
    std::vector<node> nums(n + 1);
    for (int i = 1; i <= n; i++) {
        read(nums[i].m), read(nums[i].v);
        nums[i].value = nums[i].v * 1.0 / nums[i].m;
    }
    std::sort(nums.begin() + 1, nums.end(), cmp);
    double ans = 0;
    for (int i = 1; i <= n; i++) {
        if (t >= nums[i].m) {
            t -= nums[i].m;
            ans += nums[i].v;
        } else {
            ans += nums[i].value * t;
            break;
        }
    }
    std::cout << std::fixed << std::setprecision(2) << ans << "\n";
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值