基本算法思想——贪心算法

贪心选择性质是指所求问题的整体最优解可以通过一系列局部最优的选择

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,枚举尝试,第三个欧几里得算法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

仙境觞

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

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

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

打赏作者

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

抵扣说明:

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

余额充值