小编典典

元组数

algorithm

我给了N个数字a [1..N]以及其他2个整数L和H。如何计算满足i <j <k和L <= a [i] +的元组(i,j,k)的数目a [j] + a
[k] <=H。

1 <= T <= 100
1 <= N <= 1000
1 <= L <= H <= 1000000
1 <= a[i] <= 1000000

PS:比N2logn需要更好的解决方案


阅读 876

收藏
2020-07-28

共1个答案

小编典典

由于我的C / C 有点生锈,并且这主要是算法问题,因此我将用伪代码编写(大多数情况下,正确的C / C
带有一些算法,可能需要一段时间才能写出来)。

如果您至少有sizeof(int)* 10 ^ 12字节的可用内存和时间,则可以使用时间复杂度为O(n ^ 2 * log(n))的此算法。

// Sort the N numbers using your favorite, efficient sorting method. (Quicksort, mergesort, etc.) [O(n*log(n))].
int[] b = sort(a)
int[] c = int[length(b)^2];
// Compute the sums of all of the numbers (O(n^2))
for(int i = 0; i < length(b); i++){
    for (int j = i; j < length(b); j++){
        c[i*length(b)+j] = b[i]+b[j];
    }
}

// Sort the sum list (you can do the sorts in-place if you are comfortable) - O(n^2*log(n))
d = sort(c);

// For each number in your list, grab the list of of sums so that L<=num+sum<=H O(n)
// Use binary search to find the lower, upper bounds O(log(n))
// (Total complexity for this part: O(n*log(n))
int total = 0;
for (int i = 0; i < b; i++){
    int min_index = binary_search(L-b[i]); // search for largest number <= L-b[i]
    int max_index = binary_search(H-b[i]); // search for smallest number >= H-b[i]
    total += max_index - min_index + 1; // NOTE: This does not handle edge cases like not finding any sums that work
}

return total;
2020-07-28