题解:AtCoder AT_awc0003_e Cargo Delivery Truck
本文分享的必刷题目是从蓝桥云课、洛谷、AcWing等知名刷题平台精心挑选而来并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。欢迎大家订阅我的专栏算法题解C与Python实现附上汇总贴算法竞赛备考冲刺必刷题C | 汇总【题目来源】AtCoderE - Cargo Delivery Truck【题目描述】Takahashi works at a shipping company. Today, he needs to deliverN NNpackages from the distribution center to their destinations. Each package is numbered from1 11toN NN, and packagei iiweighsW i W_iWikilograms.高桥在一家货运公司工作。今天他需要将N NN个包裹从配送中心运送到各自的目的地。每个包裹编号从1 11到N NN且包裹i ii的重量为W i W_iWi千克。The distribution center hasM MMtrucks, each numbered from1 11toM MM. Truckj jjhas a maximum load capacity ofC j C_jCjkilograms, meaning the total weight of packages loaded onto that truck must not exceedC j C_jCjkilograms. There is no limit on the number of packages loaded onto each truck, and it is acceptable for a truck to carry no packages at all.配送中心有M MM辆卡车每辆卡车编号从1 11到M MM。卡车j jj的最大载重能力为C j C_jCj千克这意味着装载到该卡车上的包裹总重量不得超过C j C_jCj千克。每辆卡车装载的包裹数量没有限制且允许卡车完全不装载任何包裹。Each package cannot be split and must be loaded onto exactly one truck. Determine whether it is possible to load allN NNpackages onto the trucks without exceeding any truck’s maximum load capacity.每个包裹不可拆分且必须装载到恰好一辆卡车上。判断是否有可能将所有N NN个包裹装载到卡车上且不超出任何卡车的最大载重能力。【输入】N NNM MMW 1 W_1W1W 2 W_2W2… \ldots…W N W_NWNC 1 C_1C1C 2 C_2C2… \ldots…C M C_MCMThe first line containsN NN, the number of packages, andM MM, the number of trucks, separated by a space.The second line containsW 1 , W 2 , … , W N W_1, W_2, \ldots, W_NW1,W2,…,WN, the weights of the packages, separated by spaces.The third line containsC 1 , C 2 , … , C M C_1, C_2, \ldots, C_MC1,C2,…,CM, the maximum load capacities of the trucks, separated by spaces.【输出】If it is possible to load all packages onto the trucks, printYes; otherwise, printNo.【输入样例】3 2 3 5 2 6 4【输出样例】No【解题思路】【算法标签】#DFS-一维#【代码详解】#includebits/stdc.husingnamespacestd;#defineintlonglongconstintN20;intn,m;// n: 货物数量m: 箱子数量intw[N],c[N],total_weight,total_capacity;// w: 货物重量c: 箱子容量boolflag;// 标记是否能装下所有货物// 深度优先搜索尝试将所有货物放入箱子voiddfs(intstep)// step: 当前处理的货物编号{if(flag)// 如果已经找到一种方案直接返回{return;}if(stepn)// 所有货物都成功放入箱子{flag1;// 标记找到可行方案return;}for(inti1;im;i)// 尝试将当前货物放入每个箱子{if(c[i]w[step])// 如果箱子容量足够{c[i]-w[step];// 放入货物dfs(step1);// 处理下一个货物c[i]w[step];// 回溯取出货物}}}signedmain(){cinnm;// 读入货物数量和箱子数量for(inti1;in;i){cinw[i];// 读入货物重量total_weightw[i];// 计算总重量}for(inti1;im;i){cinc[i];// 读入箱子容量total_capacityc[i];// 计算总容量}// 剪枝1: 如果货物总重量大于箱子总容量不可能装下if(total_weighttotal_capacity){coutNoendl;return0;}// 排序货物从重到轻箱子从大到小sort(w1,wn1,greaterint());sort(c1,cm1,greaterint());// 剪枝2: 如果最重的货物大于最大箱子的容量不可能装下if(w[1]c[1]){coutNoendl;return0;}dfs(1);// 从第一个货物开始搜索if(flag)// 如果找到可行方案{coutYesendl;}else// 否则{coutNoendl;}return0;}【运行结果】3 2 3 5 2 6 4 No