【问题标题】:How can I count the no. of subsequences that have the product of elements smaller or equal a number D?我怎么能数数。具有小于或等于数字 D 的元素的乘积的子序列?
【发布时间】:2015-12-06 10:11:36
【问题描述】:

我如何数数。数组的子序列的元素乘积小于或等于数字D 而不计算空子序列?

例如:

array=[2,2,2,3,4,10] D=50 答案应该是 39。我尝试过回溯,但速度并没有那么快。 数组中的所有数字都小于或等于D,大于0

【问题讨论】:

  • 你能发布你的代码吗?它有什么问题? 1.) 你得到不正确的结果吗,2.) 你没有得到结果是因为程序运行时间过长,还是 3.) 你得到了正确的结果但是你想要一个更快的程序吗?
  • 如果 D 足够小,你也许可以通过简单的动态规划摆脱困境
  • D ≤ 200.000 ! @尼克拉斯B。我想要的。但是我不知道怎么写!伪代码中的算法将如何?
  • 数组中元素的最大数量是多少?
  • @AndreaDusza 200.000

标签: algorithm dynamic-programming


【解决方案1】:

我的解决方案:

由于D比较小,所以我们把问题改成:

smaller and equal with D => equal with X(X = 1 to D).

解决方法equal with X

define f(x,n) = the number of the ways to product to `x` by using first n numbers.

我们会得到:

f(x,n) = f(x, n-1) + f(x div a[n], n-1) (if x mod a[n] == 0)

结合记忆,我们会得到一个O(D*n)的解。

代码如下:

__author__ = 'Sayakiss'

global a, mem

#a = [2, 2, 2, 3, 4, 10]
a = [2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 27, 29, 31, 101, 103]
mem = {}

def solve(x):
    sum = 0
    for i in range(1, x + 1):
        sum += f(i, len(a) - 1)
        #print str(i) + " " + str(f(i, len(a) - 1))
    return sum

def f(x, n):
    if x == 1:
        return 1
    if n == -1:
        return 0
    if mem.get((x, n)) is not None:
        return mem.get((x, n))
    result = 0
    if x % a[n] == 0:
        result += f(x / a[n], n - 1)
    result += f(x, n - 1)
    mem[(x, n)] = result
    return result

#print solve(50)
print solve(200000)

PS:

如果数组a中有任何1,我的解决方案将失败。但是这很容易处理,所以你可以自己做。

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2021-09-04
    • 2020-06-25
    • 2021-12-27
    相关资源
    最近更新 更多