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