首页 > 试题广场 >

糖果分配

[编程题]糖果分配
  • 热度指数: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

贪心,每颗糖果都找比它小的最大的胃口数,直接用有序表完成操作

1. import java.util.Scanner;
2. import java.util.TreeSet;
3. import static java.lang.System.in;
4. public class Main {
5.     public static void main(String[] args) {
6.         Scanner sc = new Scanner(in);
7.         String[] str = sc.nextLine().split(" ");
8.         String[] candy = sc.nextLine().split(" ");
9.         TreeSet<Integer> apiSet = new TreeSet<>();
10.         for (String item : str) {
11.             apiSet.add(Integer.parseInt(item));
12.         }
13.         int sum = 0;
14.         int temp = 0;
15.         for (String item : candy) {
16.             if (apiSet.floor(Integer.parseInt(item)) != null) {
17.                 temp = apiSet.floor(Integer.parseInt(item));
18.                 sum++;
19.                 apiSet.remove(temp);
20.             }
21.         }
22.         System.out.println(sum);
23.     }
24. }
发表于 2019-08-02 19:54:48 回复(2)
贪心算法,为了尽可能满足多的小孩,从胃口小的小孩开始,分配能最小限度满足小孩胃口的糖果。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] strG = br.readLine().trim().split(" ");
        int[] g = new int[strG.length];
        for(int i = 0; i < g.length; i++) g[i] = Integer.parseInt(strG[i]);
        String[] strS = br.readLine().trim().split(" ");
        int[] s = new int[strS.length];
        for(int i = 0; i < s.length; i++) s[i] = Integer.parseInt(strS[i]);
        Arrays.sort(s);
        Arrays.sort(g);
        int i = 0, j = 0;
        while(i < g.length){
            if(s[j] >= g[i]) {
                i++;     // 当前小孩满足,跳过
                j++;     // 当前尺寸的糖果使用掉
            }else
                j++;     // 跳过当前糖果,检查下一个更大的糖果能否满足小孩i
            if(i == g.length || j == s.length) break;
        }
        System.out.println(i);
    }
}

编辑于 2021-04-30 10:04:47 回复(0)
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
    int num;
    vector<int> g;
    vector<int> s;
    while(cin>>num)
    {
        g.push_back(num);
        if(getchar()=='\n')
            break;
    }
    while(cin>>num)
    {
        s.push_back(num);
        if(getchar()=='\n')
            break;
    }
    sort(g.begin(),g.end());
    sort(s.begin(),s.end());
    int sum=0;
    for(int i=0,j=0;j<s.size();j++)
    {
        if(i>=g.size())
            break;
        if(s[j]>=g[i])
        {
            sum++;
            i++;
        }
    }
    cout<<sum;
}
发表于 2020-02-09 09:29:03 回复(0)
#include <bits/stdc++.h> using namespace std; int main(){     string S;     vector<int> g,s;     getline(cin, S);     stringstream ss1(S);     int x, cnt=0;     while(ss1>>x)         g.push_back(x);     getline(cin, S);     stringstream ss2(S);     while(ss2>>x)         s.push_back(x);     sort(g.begin(), g.end());     sort(s.begin(), s.end());     for(int i=0,j=0;i<g.size() && j<s.size();){          if(g[i]<=s[j]){             cnt++;             i++;             j++;         }else             j++;     }     cout<<cnt<<endl;     return 0; }

发表于 2019-07-12 07:45:47 回复(0)
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)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    vector<int>g;
    vector<int>s;
    int res;
    int x;
    while(cin>>x)
    {
        g.push_back(x);
        if(cin.get()=='\n')break;
    }
    int y;
    while(cin>>y)
    {
        s.push_back(y);
        if(cin.get()=='\n')break;
    }
    sort(g.begin(),g.end());
    sort(s.begin(),s.end());
    int glen=g.size();
    int slen=s.size();
    int cur=0;
    for(int i=0;i<slen;)
    {
        if(cur>=glen)break; //满足完了就停
        while(s[i]<g[cur])i++;  //找到下一个能满足最低需求的孤儿的糖果
        if(i<slen&&cur<glen){i++;cur++;}  //判断是否找到,超过结尾表示没找到,找到执行下一次匹配
    }
    cout<<cur<<endl;
    return 0;
}
发表于 2019-08-22 22:09:53 回复(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)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string str;
    getline(cin, str);
    stringstream sin1(str);
    vector<int> g, s;
    int tmp;
    while(sin1 >> tmp) g.push_back(tmp);
    getline(cin, str);
    stringstream sin2(str);
    while(sin2 >> tmp) s.push_back(tmp);
    sort(g.begin(), g.end());
    sort(s.begin(), s.end());
    int res = 0;
    for(int i=0,j=0;i<g.size()&&j<s.size();j++)
    {
        if(s[j]>=g[i])
        {
            res++;
            i++;
        }
    }
    cout << res << endl;
    return 0;
}

发表于 2019-07-02 20:17:44 回复(0)
/*
贪心。
最大的糖果,匹配最大的学生。
*/
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str1 = in.nextLine();
        String str2 = in.nextLine();
        String[] s1 = str1.split(" ");
        String[] s2 = str2.split(" ");
        int len1 = s1.length;
        int len2 = s2.length;
        int[] arr1 = new int[len1];
        int[] arr2 = new int[len2];
        for (int i = 0; i < len1; i++) {
            arr1[i] = Integer.parseInt(s1[i]);
        }
        for (int i = 0; i < len2; i++) {
            arr2[i] = Integer.parseInt(s2[i]);
        }
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        int pos1 = len1 - 1;
        int pos2 = len2 - 1;
        int ans = 0;
        while (pos1 >= 0 && pos2 >= 0) {
            if (arr2[pos2] >= arr1[pos1]) {
                ans++;
                pos2--;
                pos1--;
            } else {
                pos1--;
            }
        }
        System.out.println(ans);
    }
}

发表于 2019-06-29 15:25:30 回复(0)
我也来贪心一个。。。
import java.util.Arrays;
import java.util.Scanner;

// 采用贪心法:谁要的少给谁分
public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        
        String line1 = scan.nextLine();
        String line2 = scan.nextLine();
        
        // 将输入的String存到int数组
        int[] childs = strToIntArray(line1);
        int[] candys = strToIntArray(line2);
        
        // ans用来保存结果
        int ans = shareCandy(childs, candys);
        System.out.println(ans);

        scan.close();
    }

    // 贪心法求解
    private static int shareCandy(int[] childs, int[] candys) {
        int ans = 0;
        // 现用内置函数从小到大排序
        Arrays.sort(childs);
        Arrays.sort(candys);
        // 从头到尾遍历两个数组,如果满足分配情况,则结果加1
        int i = 0, j = 0;
        while (i < childs.length && j < candys.length) {
            if (childs[i] > candys[j]){
                j++;
            }else{
                i++;
                j++;
                ans++;
            }
        }
        return ans;
    }
    // 将String转为数组
    private static int[] strToIntArray(String line1) {
        String[] strArr = line1.split(" ");
        int[] intArr = new int[strArr.length];
        
        for (int i = 0; i < strArr.length; i++) {
            intArr[i] = Integer.valueOf(strArr[i]);
        }

        return intArr;
    }
}


发表于 2019-10-02 08:27:55 回复(0)
//最大的糖果尽可能给胃口一样的,填完了可以给胃口小的

import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            // int a = in.nextInt();
            // int b = in.nextInt();
            // System.out.println(a + b);
            String[] s1=in.nextLine().split(" ");
            int[] children=new int[s1.length];
            for(int i=0;i<s1.length;i++){
                children[i]=Integer.parseInt(s1[i]);
            }
            Arrays.sort(children);
            String[] s2=in.nextLine().split(" ");
            int[] candies=new int[s2.length];
            for(int i=0;i<s2.length;i++){
                candies[i]=Integer.parseInt(s2[i]);
            }
            Arrays.sort(children);
            Arrays.sort(candies);
            System.out.println(getResult(children,candies));
        }
    }
    public static int getResult(int[] children, int[] candies){
        //数组是有序的
        int cnt=0;
        //最大的糖果尽可能给胃口一样的,填完了可以给胃口小的

        int pointChild=children.length-1;
        int pointCandy=candies.length-1;

        while(pointChild>=0&&pointCandy>=0){
            if(children[pointChild]<=candies[pointCandy]){
                //说明可以分配
                cnt++;
                pointCandy--;
            }
            pointChild--;
        }
        return cnt;
        
    }
}

发表于 2023-03-25 11:10:17 回复(0)
一次过
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String kid = sc.nextLine();
        String sweet = sc.nextLine();
        sc.close();
        String[] kids = kid.split(" ");
        String[] sweets = sweet.split(" ");
        int[] k = new int[kids.length];
        int[] s = new int[sweets.length];
        for(int i = 0; i < k.length; i++) {
            k[i] = Integer.parseInt(kids[i]);
        }
        for(int i = 0; i < s.length; i++) {
            s[i] = Integer.parseInt(sweets[i]);
        }
        Arrays.sort(k);
        Arrays.sort(s);
        int max = 0;
        int len = s.length - 1;
        for (int i = k.length - 1; i >= 0; i--) {
            if (len < 0) {
                break;
            }
            if (s[len] < k[i]) {
                continue;
            }
            len--;
            max++;
        }
        System.out.println(max);
    }
}


发表于 2022-09-03 19:10:27 回复(0)
贪心算法假设所有小孩都满足,糖也都发完,从最小的开始发
import java.util.Arrays;
import java.util.Scanner;

public class canddy {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String[] a=sc.nextLine().split(" ");
        int[] num1=new int[a.length];
        String[] b=sc.nextLine().split(" ");
        int[] num2=new int[b.length];
        for (int i = 0; i < a.length; i++) {
            num1[i]= Integer.parseInt(a[i]);
            System.out.print(num1[i]);
        }
        for (int i = 0; i < b.length; i++) {
            num2[i]= Integer.parseInt(b[i]);
            System.out.print(num2[i]);
        }
        Arrays.sort(num1);
        Arrays.sort(num2);
        int k=0,i=0,j=0;
        while(i< num1.length&&j<num2.length){
            if(num1[i]<num2[j])
                i++;
            else{
                i++;
                k++;
                j++;
            }
        }
        System.out.println(k);
    }
}

发表于 2022-04-03 02:26:56 回复(0)
var vals = readline().split(' ').map(str => Number(str))
var sizes = readline().split(' ').map(str => Number(str))
let res = 0
vals.sort((a,b) => a -b)
sizes.sort((a,b) => a - b)
vals.forEach(num => {
    loop:
    for (let i = 0; i < sizes.length;i++){
        if (sizes[i] >= num) {
            res += 1
            sizes.splice(0,i+1)
            break loop
        }  
    }
})
print(res)

发表于 2021-07-18 02:04:09 回复(0)
vector排序、比较、删除头元素
#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> mouth;
    vector<int> suger;
    int a, b;
    while(cin>>a){
        mouth.push_back(a);
        if(cin.get() == '\n'){
            break;
        }
    }
    while(cin>>b){
        suger.push_back(b);
        if(cin.get() == '\n'){
            break;
        }
    }
    sort(mouth.begin(),mouth.end());
    sort(suger.begin(),suger.end());
    int res = 0;
    while(!(mouth.size() == 0 || suger.size() == 0)){
        if(suger[0] >= mouth[0]){
            mouth.erase(mouth.begin());
            suger.erase(suger.begin());
            res ++;
        }
        else{
            suger.erase(suger.begin());
        }
    }
    cout<<res<<endl;
    return 0;
}
发表于 2020-09-15 09:40:59 回复(0)
#include<iostream>
(720)#include<algorithm>
#include<math.h>
using namespace std;
int main(){
    int candy[1000],kids[1000],max=0;
    int n,i=-1;
    while(cin>>n)
    {
        kids[++i]=n;
        char ch=getchar();
        if(ch=='\n')
            break;
    }
    int k=i;
    i=-1;
    while(cin>>n)
    {
        candy[++i]=n;
        char ch=getchar();
        if(ch=='\n')
            break;
    }
    sort(kids,kids+k);
    sort(candy,candy+i);
    n=i;
    int count=0,j,t=0;
    for(i=0;i<=n;i++)//kids
    {
        for(j=t;j<=k;j++)//candy
        {
            if(candy[j]>=kids[i])//条件匹配,那么累计加1,下标为j的糖果被分配出去了,下标为i的
                //kids也获得糖果,退出本循环,从下标为i++的kids分配糖果,而candy从下标为++j开始判断
            {
                count++;
                t=++j;
                break;
            }
        }
    }
    cout<<count;
    return 0;
}

发表于 2020-05-12 13:02:13 回复(0)
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;

int main(int argc, char* argv[]){
    string line1, line2;
    getline(cin, line1);
    getline(cin, line2);
    stringstream ss1(line1), ss2(line2);
    int val;
    vector<int> values, candies;
    while(ss1 >> val) values.push_back(val);
    while(ss2 >> val) candies.push_back(val);
    sort(values.begin(), values.end());
    sort(candies.begin(), candies.end());
    
    int cnt = 0, offset = 0;
    for(int idx = 0; idx < values.size(); idx++){
        auto pos = lower_bound(candies.begin()+offset, candies.end(), values[idx]);
        if(pos == candies.end()) break;
        offset = (pos - candies.begin()) + 1;
        cnt++;
    }
    cout << cnt << endl;
    return 0;
}

编辑于 2020-04-11 20:27:12 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String[] gs = sc.nextLine().split(" ");
            int[] g = new int[gs.length];
            for (int i = 0; i < gs.length; i++) {
                g[i] = Integer.parseInt(gs[i]);
            }
            String[] ss = sc.nextLine().split(" ");
            int[] s = new int[ss.length];
            for (int i = 0; i < ss.length; i++) {
                s[i] = Integer.parseInt(ss[i]);
            }
            Arrays.sort(g);
            Arrays.sort(s);
            int i = 0, j = 0, count = 0;
            while (i < g.length && j < s.length) {
                if (s[j] >= g[i]) {
                    i++;
                    count++;
                }
                j++;
            }
            System.out.println(count);
        }
    }
}

发表于 2020-04-08 17:34:55 回复(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)
C++
#include <iostream>
(720)#include <vector>
#include <sstream>
(1864)#include <string>
#include <algorithm>
 
using namespace std;
 
int func(vector<int>& g, vector<int>& s)
{
    sort(g.begin(), g.end());
    sort(s.begin(), s.end());
    int cnt = 0;
    size_t i = 0, j = 0;
    while (i < g.size() && j < s.size()) {
        if (s[j] >= g[i]) {
            ++cnt;
            ++i;
            ++j;
        }
        else
            ++j;
    }
    return cnt;
}
 
int main()
{
    vector<string> strs;
    string str;
    while (getline(cin, str, '\n'))
        strs.push_back(str);
    vector<int> g, s;
    stringstream ss1(strs[0]), ss2(strs[1]);
    while (getline(ss1, str, ' '))
        g.push_back(stoi(str));
    while (getline(ss2, str, ' '))
        s.push_back(stoi(str));
    cout << func(g, s) << endl;
    return 0;
}


发表于 2020-03-13 19:56:04 回复(0)