顾客海淘时,所购买的商品需要交给转运公司来运回国内。顾客的多个商品(假设商品都是长方体,不同的商品的长宽高可能各不相同) ,转运公司要用快递盒打包运输,但转运公司只有一种类型的快递盒,快递盒的长、宽、高都已经给定,且依据海关规定,经过海关时,若每个快递盒内所含物品的总价值不超过2000元时,可以免关税,否则要收关税。请问,转运公司收到顾客的商品之后,在希望不缴纳关税的条件下,如何用快递盒打包这些商品,需要的盒子是最少的,最少需要几个?(假设快递盒子和商品的长宽高都是int型整数)
package javatest; import java.util.ArrayList; import java.util.Scanner; public class GoodsTest { public static int MaxValue = 2000;//一个盒子的最大免税价值 public static void main(String[] args) { Scanner sc = new Scanner(System.in); BoxTemplate box = new BoxTemplate(); box.length = sc.nextInt(); box.height = sc.nextInt(); box.width = sc.nextInt(); box.price = MaxValue; int itemNum = sc.nextInt(); Model[] items = new Model[itemNum]; for (int i = 0; i < itemNum; i++) { Model item = new Model(); item.length = sc.nextInt(); item.height = sc.nextInt(); item.width = sc.nextInt(); item.price = sc.nextInt(); items[i] = item; } System.out.println("最少需要盒子个数:"+calcBoxMin(box, items)); } public static int calcBoxMin(BoxTemplate box, Model[] items) { int boxMin = 0; int[] isBoxed = new int[items.length]; for (int i = 0; i < items.length; i++) { if(isBoxed[i]==0) { ArrayList<Model> boxedItems=new ArrayList<Model>(); boxedItems.add(items[i]); isBoxed[i]=1; if(isOverflow(sum(boxedItems),box)) return -1; for(int j=i+1;j<items.length;j++) { if(isBoxed[j]==0) { boxedItems.add(items[j]); isBoxed[j]=1; Model sumItem=sum(boxedItems); if(isOverflow(sumItem,box)) { isBoxed[j]=0; boxedItems.remove(items[j]); } } } boxMin++; } } return boxMin; } public static Model sum(ArrayList<Model> items) { Model sumItem=new Model(); for(Model item:items) { sumItem.height+=item.height; sumItem.width+=item.width; sumItem.length+=item.length; sumItem.price+=item.price; } return sumItem; } public static boolean isOverflow(Model sumItem,BoxTemplate box) { if(sumItem.height>box.height) return true; if(sumItem.length>box.length) return true; if(sumItem.width>box.width) return true; if(sumItem.price>box.price) return true; return false; } } //包装盒 class BoxTemplate { int height; int width; int length; int price; } //商品 class Model { int height; int width; int length; int price; }
时间: 2024-10-07 15:07:54