gpt4 book ai didi

c++ - 元组数

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:35:07 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com