头歌资源库(8)分发饼干

一、 问题描述

二、算法思想  

       我们可以使用贪心算法来解决这个问题。首先,我们将孩子们的胃口值和饼干的尺寸进行排序,从小到大。然后,我们从最小的胃口值和最小的饼干尺寸开始匹配。

我们使用两个指针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;
}

执行结果   

 结语  

给时间时间

让过去过去

使开始开始

!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT 青年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值