一、 问题描述
二、算法思想
我们可以使用贪心算法来解决这个问题。首先,我们将孩子们的胃口值和饼干的尺寸进行排序,从小到大。然后,我们从最小的胃口值和最小的饼干尺寸开始匹配。
我们使用两个指针i和j,分别指向孩子们的胃口数组和饼干数组的起始位置。每次比较当前孩子的胃口值和饼干的尺寸,如果饼干尺寸能够满足孩子胃口,就将饼干分配给孩子,并将i和j指针往后移动一位。如果饼干不能满足孩子胃口,就将j指针往后移动一位,继续寻找下一个更大的饼干。
循环结束后,我们返回已经分配了饼干的孩子数量。
三、代码实现
#include <stdio.h>// 定义一个快速排序函数
void quickSort(int arr[], int left, int right) {if (left < right) {int i = left, j = right;int pivot = arr[left]; // 选择最左边的元素作为枢轴while (i < j) {while (i < j && arr[j] >= pivot)j--;if (i < j)arr[i++] = arr[j];while (i < j && arr[i] <= pivot)i++;if (i < j)arr[j--] = arr[i];}arr[i] = pivot;quickSort(arr, left, i - 1); // 递归排序左半部分quickSort(arr, i + 1, right); // 递归排序右半部分}
}// 分配饼干给孩子的函数
int assignCookies(int children[], int childCount, int cookies[], int cookieCount) {// 先对孩子和饼干的胃口值和尺寸进行排序quickSort(children, 0, childCount - 1);quickSort(cookies, 0, cookieCount - 1);int childIndex = 0; // 记录孩子的索引int cookieIndex = 0; // 记录饼干的索引int satisfiedChildren = 0; // 记录满足的孩子数while (childIndex < childCount && cookieIndex < cookieCount) {if (cookies[cookieIndex] >= children[childIndex]) {// 如果当前饼干能够满足当前孩子的胃口satisfiedChildren++;childIndex++; // 给这个孩子分配了饼干,检查下一个孩子}cookieIndex++; // 不管是否满足孩子,都检查下一个饼干}return satisfiedChildren;
}int main() {int m, n;scanf("%d %d", &m, &n);int g[m]; // 存储孩子的胃口值int s[n]; // 存储饼干的尺寸// 输入孩子们的胃口值for (int i = 0; i < m; i++) {scanf("%d", &g[i]);}// 输入每块饼干的尺寸for (int i = 0; i < n; i++) {scanf("%d", &s[i]);}// 调用函数计算最多能满足的孩子数int maxSatisfied = assignCookies(g, m, s, n);// 输出结果printf("%d", maxSatisfied);return 0;
}
执行结果
结语
给时间时间
让过去过去
使开始开始
!!!