贪心题目——圣诞老人的礼物

例题 圣诞老人的礼物

分发糖果,多箱不同的糖果,每箱有自己的价值和重量,每箱都可以拆分成任意散装组合带走,但是雪橇只能装下W重量的糖果,请问圣诞老人最多能敌啊走多大价值的糖果。
输入:
1⃣️n (箱子数量)W(重量)
2⃣️n行 每行给出箱子的价值和重量(整数)
输出:
最大价值(浮点数)

做法1:
价值/重量从大到小排序,再尽可能装
o(nlogn)排序

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<vector>
#include<string>
#define M 200000010
#define INF 0x3f3f3f3f
const double EPS = 1e-6;
using namespace std;
struct Candy{
    int v,w;
    bool operator < (const Candy &other)const{
        return double(v)/w - double(other.v)/other.w > EPS;
    }
}candies[100];
int main(){
    int n,w;
    cin >> n >> w;
    for(int i=0; i<n; i++){
        cin >> candies[i].v >> candies[i].w;
    }
    sort(candies,candies+10);
    double total_v=0,total_w=0;
    for(int i=0; i<n; i++){
        if(total_w+candies[i].w <= w){
            total_w += candies[i].w;
            total_v += candies[i].v;
        }
        else{
            total_v += candies[i].v * double(w-total_w)/candies[i].w;
            break;
        }
    }
    printf("%.2f\n",total_v);
    return 0;
}

贪心算法,每一步行动总是按某种指标选取最优的操作来进行,只看眼前,不考虑以后造成的影响。
贪心算法需要证明其正确性。
圣诞老人题,如果糖果只能整箱拿,那么贪心算法错误
eg
8 6
5 5
5 5
雪橇容量 10

发布了62 篇原创文章 · 获赞 0 · 访问量 1746

猜你喜欢

转载自blog.csdn.net/jhckii/article/details/104445470
今日推荐