目录
问题描述:
有一群孩子和一堆饼干,每个孩子有一个饥饿度,每个饼干都有一个大小。每个孩子只能吃最多一个饼干,且只有饼干的大小大于孩子的饥饿度时,这个孩子才能吃饱。求解最多有多少孩子可以吃饱。
输入:孩子饥饿度,饼干饱腹度
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日周日