public class Main19 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int group = Integer.parseInt(br.readLine()); List<Integer> res = new ArrayList<>(); for (int i = 0; i < group; i++) { int num = Integer.parseInt(br.readLine()); String[] letters = br.readLine().split("\\ "); int[] nums = new int[num]; for (int j = 0; j < num; j++) { nums[j] = Integer.parseInt(letters[j]); } Arrays.sort(nums); findMinValue(nums, nums.length - 1, 0); int result = 0; if (minIndex != Integer.MAX_VALUE && minIndex >= 0) { result = getMinRes(nums, minIndex); } minIndex = Integer.MAX_VALUE; res.add(result); } for (int i = 0; i < res.size(); i++) { System.out.println(res.get(i)); } } private static int minIndex = Integer.MAX_VALUE; private static void findMinValue(int[] nums, int index, int cur) { if (index < 0) { return; } if (cur + nums[index] == 0 || cur - nums[index] == 0) { minIndex = Math.min(minIndex, index - 1); } findMinValue(nums, index - 1, cur + nums[index]); findMinValue(nums, index - 1, cur - nums[index]); } private static int getMinRes(int[] nums, int index) { int result = 0; for (int i = index; i >= 0; i--) { result += nums[i]; } return result; } }
对目标数组排序,排序后从后向前遍历,用+模拟分给A的商品,用-模拟分给B的商品,加加减减直到当前商品总价值为0。递归直到找到最小的index,再从此index向下累加,和即为应抛弃货物的最小值。
想问下大佬们这个思路有问题吗
全部评论
(1) 回帖