To solve this problem, we need to count the number of subarrays in a given sequence of positive integers where the product of the elements is less than a specified value (k). Given the constraints, a brute force approach is infeasible, so we use a sliding window combined with binary search using logarithmic sums to avoid overflow and ensure efficiency.
Approach
- Logarithmic Transformation: Since the product of elements can quickly overflow, we use logarithms to convert products into sums (since (\log(a \times b) = \log(a) + \log(b))). This allows us to compare sums instead of products, avoiding overflow issues.
- Prefix Sum Array: Compute the prefix sum of the logarithms of the array elements. This helps in quickly calculating the sum of logarithms for any subarray.
- Binary Search: For each element in the array, find the smallest starting index of the subarray ending at the current element such that the sum of logarithms (equivalent to the product) is less than (\log(k)). This is done using binary search on the prefix sum array, which is strictly increasing (since all elements are positive).
Solution Code
import math
import bisect
import sys
def main():
data = list(map(int, sys.stdin.read().split()))
ptr = 0
n = data[ptr]
ptr += 1
arr = data[ptr:ptr + n]
ptr += n
k = data[ptr]
if k <= 1:
print(0)
return
log_k = math.log(k)
prefix = [0.0] * (n + 1)
for i in range(n):
prefix[i + 1] = prefix[i] + math.log(arr[i])
total = 0
for r in range(n):
current_sum = prefix[r + 1]
target = current_sum - log_k
# Find the first index in prefix[0..r] where prefix[l] > target
l_min = bisect.bisect_right(prefix, target, 0, r + 1)
total += (r - l_min + 1)
print(total)
if __name__ == "__main__":
main()
Explanation
- Logarithmic Transformation: By converting each element to its logarithm, we transform the product of a subarray into a sum of logarithms. This sum must be less than (\log(k)) for the product to be less than (k).
- Prefix Sum: The prefix sum array stores cumulative sums of logarithms. For a subarray from index (l) to (r), the sum of logarithms is (\text{prefix}[r+1] - \text{prefix}[l]).
- Binary Search: For each ending index (r), we find the smallest starting index (l_min) such that the sum of logarithms from (l_min) to (r) is less than (\log(k)). This is done using
bisect_rightto find the insertion point of the target value in the prefix array, which gives the first index where the prefix sum exceeds the target. The number of valid subarrays ending at (r) is (r - l_min + 1).
This approach efficiently handles large arrays with a time complexity of (O(n \log n)), where (n) is the length of the array, making it suitable for large input sizes. The use of logarithms ensures we avoid overflow and maintain precision.


作者声明:本文包含人工智能生成内容。