0-1背包无限整数数组?

时间:2012-05-13 05:12:59

标签: algorithm dynamic-programming

Given an infinite positive integer array or say a stream of positive integers, find out the first five numbers whose sum is twenty.

通过阅读问题陈述,它首先似乎是0-1 Knapsack问题,但我很困惑,可以在整数流上使用0-1 Knapsack algo。假设我为上述问题编写了一个递归程序。

int knapsack(int sum, int count, int idx)
{
    if (sum == 0 && count == 0)
        return 1;

    if ((sum == 0 && count != 0) || (sum != 0 && count == 0))
        return 0;

    if (arr[idx] > 20) //element cann't be included.
        return knapsack(sum, count idx + 1);

    return max(knapsack(sum, count, idx +1), knapsack(sum - arr[idx], count -1, idx + 1));
} 

现在,当上述函数调用无限数组时,max函数中的第一个调用即knapsack(sum, count, idx +1)将永远不会返回,因为它将继续忽略当前元素。即使我们在max函数中更改了调用的顺序,仍有可能第一次调用永远不会返回。有没有办法在这种情况下应用knapsack算法?

2 个答案:

答案 0 :(得分:5)

如果您只使用正整数,则此方法有效。

基本上保留一个列表,列出您可以访问前20个号码中的任何一个,并且每当您处理新号码时,都会相应地处理此列表。

def update(dictlist, num):
    dk = dictlist.keys()
    for i in dk:
        if i+num <=20:
            for j in dictlist[i]:
                listlen = len(dictlist[i][j]) + 1
                if listlen >5:
                    continue
                if i+num not in dictlist or listlen not in dictlist[i+num]:
                    dictlist[i+num][listlen] = dictlist[i][j]+[num]
    if num not in dictlist:
        dictlist[num]= {}
    dictlist[num][1] = [num]
    return dictlist

dictlist = {}
for x in infinite_integer_stream:
    dictlist = update(dictlist,x)
    if 20 in dictlist and 5 in dictlist[20]:
        print dictlist[20][5]
        break

此代码可能有一些小错误,我现在没时间调试它。但基本上dictlist [i] [j]存储一个总长为i的j长度列表。

答案 1 :(得分:0)

德尔福代码:

var
  PossibleSums: array[1..4, 0..20] of Integer;
  Value, i, j: Integer;
  s: string;
begin
  s := '';
  for j := 1 to 4 do
    for i := 0 to 20 do
      PossibleSums[j, i] := -1;
  while True do begin
    Value := 1 + Random(20); // stream emulation
    Memo1.Lines.Add(IntToStr(Value));

    if PossibleSums[4, 20 - Value] <> -1 then begin
    //we just have found 5th number to make the full sum
      s := IntToStr(Value);
      i := 20 - Value;
      for j := 4 downto 1 do begin
        //unwind storage chain
        s := IntToStr(PossibleSums[j, i]) + ' ' + s;
        i := i - PossibleSums[j, i];
      end;
      Memo1.Lines.Add(s);
      Break;
    end;

    for j := 3 downto 1 do
      for i := 0 to 20 - Value do
        if (PossibleSums[j, i] <> -1) and (PossibleSums[j + 1, i + Value] = -1) then
          PossibleSums[j + 1, i + Value] := Value;

    if PossibleSums[1, Value] = -1 then
      PossibleSums[1, Value] := Value;
  end;
end; 

输出:

4
8
9
2
10
2
17
2
4 2 10 2 2