首页 > 贪心:assign cookies分糖果

贪心:assign cookies分糖果

贪心算法的核心:

遵循某种规律,使用最少的资源来完成目标

所以在了解贪心算法的时候需要明确两点

  1. 寻找共有的规律
  2. 每一步的迭代使用最优的策略(消耗最少的资源)

问题如下:

已知一些孩子和一些糖果,每个孩子有需求因子g,每个糖果有大小s,当 某个糖果的大小s >= 某个孩子的需求因子g时,代表该糖果可以满足该孩子;求使用这 些糖果,最多能满足多少孩子?(注意,某个孩子最多只能用1个糖果满足)

类似:g = [2, 5, 9, 9, 10, 15] ,糖果大小:s = [1, 3, 6, 8, 20]

根据贪心算法的核心分析:

  1. 规律

    假如糖果大小不满足一个孩子的需求因子,则比该需求因子更小的都不会被满足

    使用最小的糖果能够满足孩子,则可以留下较大的糖果满足更高需求因子的孩子

  2. 迭代策略

    使用较小的糖果满足来满足较小需求因子的孩子

实现如下(文末有完整测试代码):

/*
需要注意:一个糖果满足了一个孩子之后就不能满足其他的孩子了
*/
int allocate_num(vector<int> &child, vector<int> &candy) { if(child.size() == 0 || candy.size() == 0) { return 0;}/*根据规律,调整糖果大小和需求因子的序列*/sort(child.begin(),child.end()); sort(candy.begin(),candy.end());int child_num = 0;int candy_num = 0;/*迭代策略:只有糖果大小 >= 孩子的需求因子之后才能算满足*/while(child_num < child.size() && candy_num < candy.size()) { if(candy[candy_num] >= child[child_num]) { child_num ++;}candy_num ++;}/*返回可以分配给孩子的数量*/return child_num;
}

测试代码如下:

#include 
#include 
#include using namespace std;int allocate_num(vector<int> &child, vector<int> &candy) { if(child.size() == 0 || candy.size() == 0) { return 0;}sort(child.begin(),child.end());sort(candy.begin(),candy.end());int child_num = 0;int candy_num = 0;while(child_num < child.size() && candy_num < candy.size()) { if(candy[candy_num] >= child[child_num]) { child_num ++;}candy_num ++;}return child_num;
}int main() { vector<int> child;vector<int> candy;int tmp_child;int tmp_candy;cout << "input child " << endl;for (int i = 0;i < 5; ++i) { cin >> tmp_child;child.push_back(tmp_child);}cout << "input candy " << endl;for (int i = 0;i < 5; ++i) { cin >> tmp_candy;candy.push_back(tmp_candy);}cout << "the num of child can be allocate is " << allocate_num(child,candy) << endl;return 0;
}

输入输出如下:

input child 
2 5 9 9 10
input candy 
1 3 6 8 20
the num of child can be allocate is 3

更多相关:

  • 给定一个以字符串表示的非负整数 num,移除这个数中的 k 位数字,使得剩下的数字最小。 注意: num 的长度小于 10002 且 ≥ k。 num 不会包含任何前导零。 示例 1 : 输入: num = “1432219”, k = 3 输出: “1219” 解释: 移除掉三个数字 4, 3, 和 2形成一个新的最小的数...

  • 代码展示:   http://paste.ubuntu.com/23693598/ #include #include #include char * largeDiffer(char *a,char *b){ /*  使用说明 传入的a和b只能为整数 结果为a-b;返回...

  • Description We all know that Bin-Laden is a notorious terrorist, and he has disappeared for a long time. But recently, it is reported that he hides in Hang Zhou of Ch...

  • /*Name: NYOJ--811--变态最大值Author: shen_渊 Date: 17/04/17 15:49Description: 看到博客上这道题浏览量最高,原来的代码就看不下去了 o(╯□╰)o */#include #include #include u...

  • 生成唯一号:思路,根据yymmddhhmmss+自增长号+唯一服务器号( SystemNo)生成唯一码,总长度19,例如:1509281204550000101. public class UniqueNumber {     private static long num = 0;//流水号     private sta...

  • 题目描述: 老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。 你需要按照以下要求,帮助老师给这些孩子分发糖果: 每个孩子至少分配到 1 个糖果。 相邻的孩子中,评分高的孩子必须获得更多的糖果。 那么这样下来,老师至少需要准备多少颗糖果呢? 示例 1: 输入: [1,0,2] 输...