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
The key insight here is to transform the problem into a more manageable form. Let's define a new array (C) where (C[k] = A[k] - B[k]). The original condition (A[i] + A[j] > B[i] + B[j]) can be rewritten as (C[i] + C[j] > 0).
Now, the problem reduces to counting the number of pairs (i, j) with i < j and (C[i] + C[j] > 0). To do this efficiently:
- Sort the array (C) in ascending order.
- Use two pointers to count valid pairs:
- Start with left at the beginning and right at the end of the sorted array.
- If (C[left] + C[right] > 0), all elements from left to right-1 will form valid pairs with right, so add the count of these elements to the result and move right leftwards.
- If (C[left] + C[right] \leq 0), move left rightwards to find a larger element that can form a valid pair with right.
Solution Code
def main():
import sys
input = sys.stdin.read().split()
ptr = 0
N = int(input[ptr])
ptr +=1
A = list(map(int, input[ptr:ptr+N]))
ptr +=N
B = list(map(int, input[ptr:ptr+N]))
C = [a - b for a, b in zip(A, B)]
C.sort()
left = 0
right = N-1
count =0
while left < right:
if C[left] + C[right] > 0:
count += right - left
right -=1
else:
left +=1
print(count)
if __name__ == "__main__":
main()
Explanation
- Transformation: By converting the problem to using array (C), we simplify the condition to checking sums of pairs in (C).
- Sorting: Sorting (C) allows us to use the two-pointer technique, which is efficient and runs in linear time after sorting.
- Two-pointer Technique: This technique helps us count valid pairs in (O(N)) time after sorting, making the overall complexity (O(N \log N)) (due to sorting), which is optimal for the given constraints.
This approach efficiently handles the problem and ensures that we count all valid pairs without missing any or counting duplicates. The solution is both time and space efficient, making it suitable for large input sizes.


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