快递运输

【快递运输】
一辆运送快递的货车,运送的快递均放在大小不等的长方体快递盒中,为了能够装载更多的快递,同时不能让货车超载,需要计算最多能装多少个快递。
注:快递的体积不受限制,快递数最多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;
}

#笔试题目#
全部评论
有 js 版本吗
1 回复 分享
发布于 2022-04-21 10:08
Java 版本: public class T1Main {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);         while (scanner.hasNext()) {             // 封装值             String str = scanner.nextLine();             Integer total = scanner.nextInt();             Set<Integer> ws = new TreeSet<>();             for (String item : str.split(",")) {                 ws.add(Integer.parseInt(item));             }             // 简单贪心算法             Integer num = 0;             Integer c = 0;             for (Integer w : ws) {                 c += w;                 if (c > total) {                     break;                 }                 num++;             }             System.out.println(num);         }     } }
点赞 回复 分享
发布于 2022-06-06 16:04

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
评论
点赞
4
分享

创作者周榜

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