n个元素之间的最小差异

时间:2013-03-08 10:19:51

标签: algorithm language-agnostic

我正在使用C ++开发一个项目。我有n个元素intK

我需要找到一种方法来获取min{a1+a2+....+an} - K <= ε >= 0,其中ε=最小数字。

数字组合可以是{a1+a2+a6},也可以是{a2}{a2+an},我的意思是它不像find(n k)组合。

我正在研究小n(n <15),因此复杂性不是问题。

3 个答案:

答案 0 :(得分:2)

想象一下,您找到了问题的多项式解,即您可以找到其总和最接近K的数字子集。

现在想象一下这个算法:

- Find the subset of numbers with sum closest to K
- If (sum(subset) - K == 0)
-     return subset
- Else
-     return DOESNT_EXIST

这个算法是什么? the subset-sum problem的多项式解法!

由于P = NP的可能性很小,因此您不太可能找到任何可扩展的解决方案。

换句话说,你坚持使用蛮力。

答案 1 :(得分:0)

您可以使用位掩码进行暴力攻击。像这样:

#include <iostream>
using namespace std;

int main()
{
    int n = 15;
    int a[] = {8, 6, 14, 3, 4, 11, 100, 24, 41, 56, 18, 22, 11, 39, 91};
    int k = 16;
    int best_sum = -1;
    int best_i = -1;
    for(int i = 0; i < (1 << n); i++) {
        int sum = 0;
        for(int j = 0; j < n; j++) {
            if((i >> j) & 1) {
                sum += a[j];
            }
        }
        if(sum >= k && (best_sum == -1 || sum < best_sum)) {
            best_sum = sum;
            best_i = i;
        }
    }
    cout << best_sum << " ->";
    for(int j = 0; j < n; j++) {
        if((best_i >> j) & 1) {
            cout << " " << a[j];
        }
    }
    cout << endl;
    return 0;
}

答案 2 :(得分:0)

我打算为此编写伪代码:

您可以使用值列表创建可排序的地图。并在地图中放入a1..n元素的一个值及其值。并且将set compare方法插入&lt; 地图看起来像:

[n] [value]

列表将是ASC

要获得最小的数字,你可以从头开始进行列表操作并执行+操作直到mapelement [0] + mapelement [1]&gt; e + K

你将得到一张地图的第一个元素列表,其n值为

相关问题