用于查找最重的袋子的最小重量的Java算法

时间:2018-03-01 06:04:02

标签: java algorithm

给定一定数量的物品和行李,如果必须连续添加 ,请找到最重行李的最小重量。

示例:

  • 行李数:3

  • 项目数量:9

  • 每个项目的重量顺序: 10 20 30 40 50 60 70 80 90

因此:

  • 第一个包将包含项目1到5,重量总计为150。 (10 + 20 .. + 50)

  • 第二个包将包含项目6到7,重量总计为130。 (60 + 70)

  • 第三个包将包含物品8至9,重量总计为170。 (80 + 90)

因此,最重的袋子的最小重量将是袋子3,重量为170,注意每个物品是连续添加的,即袋子1不包含第1项和第4项,但跳过2和3。

我的算法:

public class Packing {
    private void run() {

      //take in necessary input.
        Scanner sc = new Scanner(System.in);
        String[] input = sc.nextLine().split(" ");
        int items = Integer.parseInt(input[0]);
        int luggage = Integer.parseInt(input[1]);

      //parse each item's weight into an array.
        int[] weight = Arrays.stream(sc.nextLine().split(" "))
            .mapToInt(Integer::parseInt).toArray();

      //get total weight of all items.
        long sum = Arrays.stream(weight).sum();

      //new array to hold weight of each bag.
        int[] container = new int[luggage];

        int j = 0;

      //for each remaining item, check if current bag's weight is larger then
      the average weight of the remaining item vs remaining bags. else, increment
      the bag counter and put the next item in the new bag.

        for (int i = 0; i < items; i++) {

            long avg = sum/(luggage - j);

            if (container[j] < avg) {
                container[j] += weight[i];
            } else {
                if(j < luggage - 1){
                    j++;
                }
                container[j] += weight[i];
            }
            sum = sum - weight[i];
        }
        List<Integer> list = Arrays.stream(container).boxed().collect(Collectors.toList());
        System.out.println(Collections.max(list));
        sc.close();
    }
    public static void main(String[] args) {
        Packing newPacking = new Packing();
        newPacking.run();
    }
}

例如,开始时的平均权重为450/3 = 150。 当前行李没有物品,第一件物品的重量为10.自10 < 150起,请将此物品添加到第一个行李中。

加权平均值现在是:

450 - 10 / 3 (remaining bags). = 146.67..

直到添加当前项目结果导致当前行李超过平均值。然后当前项目转到下一个包,平均值将重新计算为(remaining weight)/(remaining bags),其中剩余行李为3 - 1 = 2

这个算法对我的第一个测试用例没问题,但是其余的都没用了:这是另一个测试用例的例子。

  • 行李数:3

  • 项目数量:10

  • 每个项目的重量顺序: 722 94 195 78 649 833 705 941 766 958

答案应该是:2479, (833+705+941)但我得到2665

有没有合适的算法来解决这个问题?

0 个答案:

没有答案