快递运输

【快递运输】
一辆运送快递的货车,运送的快递均放在大小不等的长方体快递盒中,为了能够装载更多的快递,同时不能让货车超载,需要计算最多能装多少个快递。
注:快递的体积不受限制,快递数最多1000个,货车载重最大50000。
输入描述:
    第一行输入每个快递的重量,用英文逗号分隔,如:5,10,2,11
    第二行输入货车的载重量,如:20
    不需要考虑异常输入。

输出描述:
    输出最多能装多少个快递,如:3

示例1:
输入
    5,10,2,11
    20

输出
    3
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
vector<int> splitString(string &str, char flag)
{
    vector<int> result;
    istringstream floatStr(str);
    string temp;
    while (getline(floatStr, temp, flag)) {
        result.push_back(stoi(temp));
    }
    return result;
}

int main()
{
    string str = "";
    cin >> str;

    int weight = 0;
    cin >> weight;

    vector<int> result = splitString(str, ',');
    sort(result.begin(),result.end());

    int sum = 0;
    int res = 0;
    for (size_t i = 0; i < result.size(); i++) {
        sum += result[i];
        if (sum <= weight) {
            res++;
            continue;
        }
        break;
    }

    cout << res;
    return 0;
}

import java.util.*;

public class Main{
    
    private static int[] getWeights(String str) {
        if (str==null || str.length()<=0) {
            return new int[0];
        }
        // 分割字符串
        String[] arr = str.split(",");
        int[] result = new int[arr.length];
        // 将每个字符串数据装成int,数组形式返回
        for (int i=0;i<arr.length;++i) {
            result[i] = Integer.valueOf(arr[i]);
        }
        return result;
    }
    
    private static int getMaxNum(String weightStr, int upBorder) {
        int[] weights = getWeights(weightStr);
        // 执行一遍排序,确保所有的小重量包裹在前。简化计算
        Arrays.sort(weights);
        int index = 0;
        while(index<weights.length && upBorder>=weights[index]){
            upBorder -= weights[index];
            index++;   
        }
        return index;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String weightStr = scanner.nextLine();
        int upBorder = scanner.nextInt();
        System.out.println(getMaxNum(weightStr, upBorder));
    }
}


while True:
    try:
        kd_list = [int(i) for i in input().split(',')]
        height = int(input())
        kd_list.sort()
        sum = height
        sun = 0
        for k in kd_list:
            if sum >= k:
                sun += 1
                sum -= k
            else:
                break
        print(sun)
    except:
        break  
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-10 15:24
高考前一晚在OPPO手机上设置了早上5:30的闹钟,然而闹钟并未按时响起。直到妈妈做好早餐后,在6:27打开手机才发现闹钟未触发,“气得早上饭都没吃”。资本家你赢了
永不遗忘:我来解释一下 :Oppo 手机晚上两点会自动进行系统更新,这个系统更新会重置掉所有设置好的闹钟,而且他也不会告诉你,而且只有 Oppo 会这样,华为苹果小米三星都不会
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务