首页 > 试题广场 >

糖果分配

[编程题]糖果分配
  • 热度指数:6866 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
假设你是一位很有爱的幼儿园老师,想要给幼儿园的小朋友们一些小糖果。但是,每个孩子最多只能给一块糖果。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的糖果的最小尺寸;并且每块糖果 j ,都有一个尺寸 s。如果 sj >= g,我们可以将这个糖果 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
注意:
你可以假设胃口值为正。
一个小朋友最多只能拥有一块糖果。


输入描述:
第一行输入每个孩子的胃口值

第二行输入每个糖果的尺寸

孩子数和糖果数不超过1000


输出描述:
能满足孩子数量的最大值
示例1

输入

1 2 3
1 1

输出

1
def solution(weights,sweets):
    weights = sorted(weights)  # 胃口
    sweets = sorted(sweets)
    count = 0 
    j = 0  
    for i in range(len(weights)): 
        while j < len(sweets): 
            if sweets[j] >=weights[i]:
                count += 1  
                j += 1  
                break  
            else:
                j += 1  
    return count 
if __name__ == '__main__':
    weights = list(map(int, input().strip().split()))
    sweets = list(map(int, input().strip().split())) 
    print(solution(weights, sweets))


发表于 2020-06-19 14:14:18 回复(0)
G=list(map(int,input().split()))
S=list(map(int,input().split()))
def getNum(G,S):
    G.sort();
    S.sort();
    res,i,j=0,0,0;
    l1,l2=len(G),len(S)
    while i<l1:
        while j<l2:
            if S[j]>=G[i]:
                res+=1;
                j+=1;
                break;
            else:j+=1;
        else:
            break;
        i+=1
    return res

print(getNum(G,S))
        
            
    

发表于 2020-03-14 11:28:24 回复(0)
import sys
g=list(map(int,sys.stdin.readline().split()))
s=list(map(int,sys.stdin.readline().split()))
g.sort()
s.sort()
num=0
for j in s:
    for i in g:
        if j>=i:
            num+=1
            g.remove(i)
            break
print(num)

发表于 2019-09-14 17:16:26 回复(0)
def f(childs, tang):
    childs = sorted(childs)
    tang = sorted(tang)
    c = 0; t = 0
    count=0
    for i in range(c, len(childs)):
        for j in range(t, len(tang)):
            if childs[i]<=tang[j]:
                count+=1
                c +=1
                t+=1
                break
            else:
                t+=1
                continue
    print(count)
childs = list(map(int, input().split()))
tang =  list(map(int, input().split()))
f(childs, tang)
发表于 2019-08-15 23:41:44 回复(0)
"""
贪心法,剩余最大糖果分给能满足胃口且胃口最大的孩子
"""
import sys

if __name__ == "__main__":
    # sys.stdin = open("input.txt", "r")
    g = list(map(int, input().strip().split()))
    s = list(map(int, input().strip().split()))
    g.sort()
    s.sort()
    i = len(g) - 1
    j = len(s) - 1
    ans = 0
    while i >= 0 and j >= 0:
        if s[j] >= g[i]:
            ans += 1
            j -= 1
        i -= 1
    print(ans)

发表于 2019-07-10 17:20:15 回复(0)