Sum-of-Product of subsets

后端 未结 2 1781
没有蜡笔的小新
没有蜡笔的小新 2020-12-31 16:12

Is there a name for this operation? And: is there a closed-form expression?

  • For a given set of n elements, and value k between 1 and n,
  • Take all subs
2条回答
  •  爱一瞬间的悲伤
    2020-12-31 16:25

    These are elementary symmetric polynomials. You can write them using summation signs as in Wikipedia. You can also use Vieta's formulas to get all of them at once as coefficients of a polynomial (up to signs)

    (x-a_1)(x-a_2)...(x-a_k) =
       x^k -
       (a_1 + ... + a_k) x^(k-1) +
       (a_1 a_2 + a_1 a_3 + ... + a_(k-1) a_k)) x^(k-2) +
       ... +
       (-1)^k a_1 ... a_k
    

    By expanding (x-a_1)(x-a_2)...(x-a_k) you get a polynomial time algorithm to compute all those numbers (your original implementation runs in exponential time).

    Edit: Python implementation:

    from itertools import izip, chain
    
    l = [2,3,4]
    
    x = [1]    
    for i in l:
        x = [a + b*i for a,b in izip(chain([0],x), chain(x,[0]))]
    print x
    

    That gives you [24, 26, 9, 1], as 2*3*4=24, 2*3+2*4+3*4=26, 2+3+4=9. That last 1 is the empty product, which corresponds to k=0 in your implementation.

    This should be O(N2). Using polynomial FFT you could do O(N log2 N), but I am too lazy to code that.

提交回复
热议问题