To solve this problem, we need to count the number of valid pairs (i, j) such that (i < j) and (A[i] + A[j] > B[i] + B[j]).
Approach
-
Transform the Problem: Rearrange the given condition to simplify it. The condition (A[i] + A[j] > B[i] + B[j]) can be rewritten as ((A[i] - B[i]) + (A[j] - B[j]) > 0). Let (C[k] = A[k] - B[k]) for all (k). Now the problem reduces to finding the number of pairs (i, j) where (i < j) and (C[i] + C[j] > 0).
-
Sort the Array: Sorting the array (C) helps in efficiently finding valid pairs using binary search. For each element (C[j]), we need to find the smallest index (i < j) such that (C[i] > -C[j]).
-
Binary Search: For each (j), use binary search to find the position where elements start to be greater than (-C[j]). The number of valid pairs for (j) is the count of elements from this position to (j-1).
Solution Code
import bisect
import sys
def main():
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
b = list(map(int, sys.stdin.readline().split()))
c = [a[i] - b[i] for i in range(n)]
c.sort()
total = 0
for j in range(1, n):
target = -c[j]
pos = bisect.bisect_right(c, target, 0, j)
total += (j - pos)
print(total)
if __name__ == "__main__":
main()
Explanation
- Transformation: By defining (C[k] = A[k] - B[k]), we convert the original problem into finding pairs in (C) that sum to a positive value.
- Sorting: Sorting (C) allows us to use binary search to quickly find valid pairs.
- Binary Search: For each element (C[j]), we find the first index (pos) where (C[pos] > -C[j]). The number of valid pairs for (j) is (j - pos) because all elements from (pos) to (j-1) are greater than (-C[j]), hence their sum with (C[j]) is positive.
This approach has a time complexity of (O(N \log N)) due to sorting and binary search operations, which is efficient for large values of (N) (up to (100,000)). The space complexity is (O(N)) for storing the array (C).
This solution efficiently handles all edge cases and provides the correct count of valid pairs.


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