贪心选择性质是指所求问题的整体最优解可以通过一系列局部最优的选择
1.分配问题
有一群孩子和一堆饼干,每个孩子有一个饥饿度,每个饼干都有一个大小,每个孩子只能吃最多一个饼干,且只有饼干的大小大于孩子的饥饿度是,这个孩子才能吃饱,求解最多有多少孩子能吃饱。
输入输出样例
输入:1 2
1 2 3
输出:2
问题分析
贪心选择性质是指所求问题的整体最优解可以通过一系列局部最优的选择,题目求最多有多少孩子能吃饱。所以以每个孩子吃的最少作为局部最优的选择。
代码实现
#include <stdlib.h>
#include <stdio.h>
//冒泡排序
void bulleSort(int *array, int length)
{
int tmp;
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1; j++)
{
if (array[j] > array[j + 1])
{
tmp = array[j + 1];
array[j + 1] = array[j];
array[j] = tmp;
}
}
}
}
//读取数组
void printfArray(int *array, int length)
{
printf("array[]={");
for (int i = 0; i < length - 1; i++)
{
printf("%d,", array[i]);
}
printf("%d}", array[length - 1]);
}
int solution(int *children, int childrenSize, int *cookie, int cookieSize)
{
int child = 0; //能吃饱孩子的数量
int cook = 0;
while (child < childrenSize && cook < cookieSize)
{
if (children[child] <= cookie[cook])
{
child++;
cook++;
}
else
{
cook++;
}
}
return child;
}
int main()
{
int children[] = {1, 2, 55, 36, 77};
int cookie[] = {1, 4, 3, 6, 9, 8, 22, 6, 5, 56};
int length = sizeof(cookie) / sizeof(cookie[0]);
int childrenSize = sizeof(children) / sizeof(children[0]);
bulleSort(cookie, length);
bulleSort(children, childrenSize);
printf("\narray is length=%d\n", length);
//贪心算法解决问题
int childNumber = solution(children, childrenSize, cookie, length);
printf("child number = %d\n", childNumber);
//结尾
printf("\n\n\n");
system("pause");
return 0;
}
//两个数的最大公因素,ppt,枚举尝试,第三个欧几里得算法