c++ - 元组数

标签 c++ c algorithm

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

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

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

最佳答案

解决方案

由于我的 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;

关于c++ - 元组数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13216041/

相关文章:

c++ - 表达式中使用的枚举数是否与其枚举的基础类型具有相同的类型?

c - C语言K&R中的atoi函数

c++ - 如何将 IStream 的内容转储(写入)到文件中(图片)

python - 第一行的累积减法

c++ - 获取模板可调用对象的参数类型

c++ - CUDA 袖带 2D 示例

c++ - DEBUG : During Hook procedure call , 它显示 vsjitdebugger.exe 错误

c++ - 在 C++ OpenMP 中以两种方式使用蒙特卡洛方法计算 pi

algorithm - 简单、重要的装箱实例

c++ - wintun:注册环形缓冲区时出现ERROR_INVALID_PARAMETER