求帮助,非常需要,蟹!c++代码,感觉有点像贪心,20分钟

求帮助,非常需要,蟹蟹!c++代码,感觉有点像贪心,20分钟可以做出来吗,

img

img

你题目的解答代码如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
using namespace std;
struct map
{
    int w;
    int p;
    double f;
};
bool comp(map a,map b) {
    return a.f < b.f;
}
int main()
{
    int n,num,i,j;
    double sum = 0;
    cin >> n >> num;
    map a[n];
    for (i = 0; i < n; i++)
    {
        cin >> a[i].w >> a[i].p;
        a[i].f = a[i].p*1.0/a[i].w;
    }
    sort(a,a+n,comp);
    for (i = 0; i < n; i++)
    {
        if (num>=a[i].p)
        {
            sum += a[i].w;
            num -= a[i].p;
        }
        else
        {
            sum += num/a[i].f;
            break;
        }
    }
    cout << fixed << setprecision(2) << sum << endl;
    return 0;
}

img

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632