编程语言
首页 > 编程语言> > 【算法笔记】Day08 | 4.4贪心

【算法笔记】Day08 | 4.4贪心

作者:互联网

本节目录

4.4.1 简单贪心

A.定义

在这里插入图片描述

B.举例1–月饼

b1.题意

在这里插入图片描述

b2.思路

在这里插入图片描述

b3.注意点

在这里插入图片描述

b4.代码

//4_4_1
#include<cstdio>
#include<algorithm>
using namespace std;
struct mooncake {
    double store;//库存量
    double sell;//总售价
    double price;//单价
}cake[1010];
bool cmp(mooncake a,mooncake b){
    return a.price > b.price;
}
int main(){
    int n;
    double D;
    scanf("%d%1f",&n,&D);
    for(int i =0 ;i < n ;i++){
        scanf("%1f",&cake[i].store);
    }
    for(int i = 0;i < n ; i++ ){
        scanf("%1f",&cake[i].sell);
        cake[i].price = cake[i].sell / cake[i].store;//计算单价
    }
    sort(cake, cake + n,cmp);//按照单价从告到低排序
    double ans = 0;//收益
    for(int i = 0;i < n; i++){
        if(cake[i].store <= D){//如果需求量高于库存量
            D -=  cake[i].store;//第i种月饼全部卖出
            ans += cake[i].sell;
        }else{//如果月饼库存量高于需求量
            ans += cake[i].price * D;//值卖出剩余需求量的月饼
            break;
        }
    }
    printf("%.2f\n",ans);
    return 0;
}

标签:4.4,Day08,int,double,price,ans,cake,store,贪心
来源: https://blog.csdn.net/qq_43134199/article/details/113731295