贪心法——分配饼干

目录

问题描述:

问题分析:

算法实现:

问题描述:

有一群孩子和一堆饼干,每个孩子有一个饥饿度,每个饼干都有一个大小。每个孩子只能吃最多一个饼干,且只有饼干的大小大于孩子的饥饿度时,这个孩子才能吃饱。求解最多有多少孩子可以吃饱。

输入:孩子饥饿度,饼干饱腹度

8 4 2 6 7

1 4 2 3

输出:吃饱孩子个数

2

问题分析:

首先给孩子饥饿度chileren[n]和饼干大小cookies[m]由小到大进行排序,我们希望最小的饼干能给饥饿度最小的孩子,实现物尽其用,用最小的成本实现尽可能大的问题。优先考虑饥饿度小的孩子。

算法实现:

​
​
#include <iostream>
using namespace std;

const int MAX = 1000;
int n = 0,m = 0;//一共有n个孩子,m块饼干
int children[MAX];//孩子的饥饿值
int cookies[MAX]; //饼干的饱腹感
int child = 0;//吃饱的孩子的数量
int cookie = 0;//当前指向的饼干

//插入排序
int insert_sort(int a[],int n){
    if(n == 1)return 0;
    for(int j = 1; j < n; j++){
        int key = a[j];
        for(int i = j-1; i >= 0; i--){
            if(a[i] > key){
                swap(a[i+1],a[i]);
            }
            else break;
        }
    }
    return 0;
}



//数组输出函数
void disp(int a[],int n){
    cout<<"The sorted array is shown below"<<endl;
    for(int i = 0; i < n; i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

int solution(int children[] , int cookies[]){
    insert_sort(children,n);
    insert_sort(cookies,m);
    while(child < n && cookie < m){
        if(cookies[cookie] >= children[child]){
            child++;
        }  
        cookie++;
    }
    return child;
}
int main(){
    /*
     *现在有8个孩子,饥饿值为8 4 2 6 7 9 10
     *一共有5块饼干,饼干值为1 4 2 3 5
     *一个孩子只能吃一块饼干,问:最多多少个孩子可以吃饱?
    */

    cout<<"Please enter the child's hunger value!"<<endl;
    while(1){
        cin>>children[n];
        if(children[n] <= 0)break;
        n++;
    }
    cout<<"Please enter the satiety value of the biscuit!"<<endl;
    while(1){
        cin>>cookies[m];
        if(cookies[m] <= 0)break;
        m++;
    }
    child = solution(children,cookies);
    cout<<"The number of children fed is "<<child<<endl;
    
}

​

​

——(yu)2023年5月14日周日

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值