【问题标题】:Walrus Weights/Getting a combination in an array whose sum is closest 1000海象权重/在总和最接近 1000 的数组中获取组合
【发布时间】:2016-04-16 01:21:35
【问题描述】:

我一直在解决这个问题https://open.kattis.com/problems/walrusweights。我看到这里有人问过这个问题,但是我对这个问题的处理方式完全不同。

在这个问题中,你必须在一个数组中找到一个总和最接近 1000 的组合。这是我的解决方案,它在时间限制(0.26s,限制为 2s)下运行良好,但是,在 31 个测试用例之后,它给我错误的答案。

在我的程序中,我首先读取所有的数字,并将其变成一个大小为 n + 1 的数组(第一个数字是 0,我稍后会解释),然后调用这个方法:

public static void combination(int index, boolean use, int currentSum, int closest){
    HS.add(currentSum);
    HS.add(closest);
    if(index == size){
        return;
    }
    if(use)
        currentSum += array[index];
    index++;
    if(currentSum == 0){ //would interfere with the if statement below, if it's 0, it will always be closer to 1000 
        combination(index, true, currentSum, closest);
        combination(index, false, currentSum, closest);
    }
    else{
        if(Math.abs(1000 - currentSum) < Math.abs(1000 - closest)){//so, if the currentSum is closer to 1000 than the closest so far
            closest = currentSum; //this is now the closest one
        }
        else //otherwise, there's no point going on with further changes to this combination, it will never be closest
            return;
        combination(index, true, currentSum, closest);
        combination(index, false, currentSum, closest);
    }
}

与:

combination(0, nums, false, 0, 1000001); //limit of weights is 1000000

在组合方法中,参数是您当前所在的索引、数组、是否将当前条目添加到总和、当前总和以及迄今为止最接近 1000 的最高组合。

我做了一个方法,一旦所有的组合都完成了,它会得到一个最接近 1000 的方法,但我确信它有效,而且它非常简单,所以不值得展示,除非需要。

谁能告诉我我做错了什么?组合方法的逻辑是否不正确,或者是否有额外的检查或我缺少的那种东西?

【问题讨论】:

  • 你有什么问题?
  • 糟糕,我的错,刚刚编辑了它。对不起。

标签: java walrus


【解决方案1】:

有点晚了,但我已经回答了这个问题,并将其留在这里让其他人看看他们是否需要。

http://hastebin.com/etapohavud.cpp

我创建了一个遍历数字数组(之前已排序)的递归方法,只检查可能导致最接近的数字的和,并将所有可能的数字添加到 ArrayList 中。它已排序,因此我不必担心会在前面找到一个较小的数字,这可能会改变我正在检查的整个当前总和。

简而言之,我计算了所有可行组合,最终可能最接近 1000,然后找到最接近它的一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2012-10-30
    • 1970-01-01
    相关资源
    最近更新 更多