在数组中获取k个数字因子的问题

时间:2019-05-27 12:03:38

标签: algorithm

我有一个 N 个数字数组 Arr = [a1,a2,.. aN],元素数量 K 和数字<我需要通过乘以 Arr 中的 K 个元素来获得strong> M 。
如何以最快的方式做到这一点?

例如, Arr = [1、2、3、4、5、6、12], M = 12, K = 2。
解决方案为:(1,12),(3,4),(2,6)。
如果 K = 3,则答案为:(1,2,6),(1,3,4)。
我需要至少获得以下解决方案之一才能找到正确的答案。

我使用meet-on-the-middle method在Python 3上编写了一个程序 但我认为有更好的解决方案。
这是我执行此任务的代码,在输入文件中,我们有:

6 12 3
1 2 3 4 5 6

,我的代码返回元素的索引,从1开始。此输入的答案是:

1 2 6
from itertools import combinations

with open("input.txt") as input:
    n, m, k = tuple(map(int, input.readline().split(" ")))
    array = list(map(int, input.readline().split(" ")))

    separ = n // 2

    first = dict()
    second = dict()
    minimum = min(k, separ + 1) + 1
    for amount in range(minimum):
        first[amount] = {}
        for comb in combinations(range(separ), amount):
            score = 1
            for i in comb:
                score *= array[i]
            first[amount][score] = comb

    for amount in range(minimum):
        second[amount] = {}
        for comb in combinations(range(separ, n), amount):
            score = 1
            for i in comb:
                score *= array[i]
            second[amount][score] = comb

    # print(second, first)
    for count1 in first:
        for score1 in first[count1]:
            if score1 != 0:
                if second.get(k - count1) and second[k - count1].get(m / score1) is not None:
                    print((" ".join([str(x + 1) for x in first[count1][score1]]) + " " + " ".join([str(y + 1) for y in second[k - count1][m / score1]])).strip())
                    exit()
            elif m == 0:
                if second.get(k - count1) is not None:
                    print((" ".join([str(x + 1) for x in first[count1][score1]]) + " " + " ".join(
                        [str(y + 1) for y in next(iter(second[k - count1].values()))]).strip()))
                    exit()
            else:
                continue

0 个答案:

没有答案