假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i,都有一个胃口值g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j]。如果 s[j]>= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。请设计算法尽可能满足越多数量的孩子,并输出这个最大数值。输入数据包括三行,第一行输入孩子数m和饼干数n,第二行是孩子们的胃口值,第三行是每块饼干的尺寸。
例如,输入:
3 2
1 2 3
1 1
则输出:1
再例如,输入:
2 3
1 2
1 2 3
则输出:2
#include<stdio.h>
//降序排列
void sift(int r[], int root, int leng)
{
int rootS = root;
int t = r[root];
int rootKey = r[root];
int child = root * 2;
_Bool finished = 0;
while (child <= leng && !finished)
{
if (child + 1 <= leng && r[child] > r[child + 1])
child = child + 1;
if (rootKey <= r[child])
finished = 1;
else
{
r[rootS] = r[child];
rootS = child;
child = rootS * 2;
}
}
r[rootS] = t;
}
void crt_heap(int r[], int leng)
{
for (int i = leng / 2; i > 1; i--)
sift(r, i, leng);
}
void heap(int r[], int leng)
{
int end;
crt_heap(r, leng);
for (int i = leng; i >= 2; i--)
{
end = r[1];
r[1] = r[i];
r[i] = end;
sift(r, 1, i - 1);
}
}
int main()
{
int i = 0, j = 0, k = 1;
int chiCun[100] = { 0 }, weiKou[100] = { 0 }, satis[100] = {0};
int kids, cookies;
int satisfied = 0;
scanf("%d %d", &kids, &cookies);//输入孩子数,饼干数
for (int k = 1; k <= kids; k++)
{
scanf("%d", &i);
weiKou[k] = i;
}
for (int c = 1; c <= cookies; c++)
{
scanf("%d", &j);
chiCun[c] = j;
}
heap(weiKou, kids);// 降序排列孩子胃口
heap(chiCun, cookies);//降序排列饼干尺寸
printf("\n");
for (int c = 1; c <= cookies; c++)
{
for (; k <= kids; k++)
{
if (weiKou[k] <= chiCun[c] && satis[k] == 0)
{
satisfied++;
satis[k] = 1;
break;
}
}
}
printf("%d", satisfied);
}
其实主要思想就是把孩子胃口和饼干尺寸排序,然后遍历,若饼干尺寸大于孩子胃口就把被满足的孩子数加一。
个人感言:这是我们天杀的算法作业,在头歌这个逆天平台上提交,只要一点不符合提交格式就会被打回,而且我们老师说什么都不行就只要C语言,一个代码写30分钟改格式改3个小时,我现在粘贴的这个代码其实就是不符合格式的,所以仅做留档用,如果能帮到你自然最好不过。