太难了``` import bisect
def main(): import sys import sys input = sys.stdin.read().split() ptr = 0 T = int(input[ptr]) ptr += 1
results = []
for _ in range(T):
n = int(input[ptr])
ptr += 1
pairs = []
for _ in range(n):
a = int(input[ptr])
b = int(input[ptr+1])
ptr += 2
pairs.append((a, b))
# Collect all unique prices
all_prices = set()
for a, b in pairs:
all_prices.add(a)
all_prices.add(b)
all_prices = sorted(all_prices)
# Sort pairs based on the first element
sorted_pairs = sorted(pairs, key=lambda x: x[0])
a_sorted = [a for a, b in sorted_pairs]
b_sorted = [b for a, b in sorted_pairs]
# Precompute max_b_after for each position
max_b_after = [0] * n
max_b_after[-1] = b_sorted[-1]
for i in range(n-2, -1, -1):
max_b_after[i] = max(b_sorted[i], max_b_after[i+1])
ans = float('inf')
for a_candidate in all_prices:
# Find the position where a_candidate would be inserted in a_sorted
pos = bisect.bisect_right(a_sorted, a_candidate)
# Determine the required_max_b
if pos < n:
required_max_b = max_b_after[pos]
else:
required_max_b = -float('inf')
# Determine the lower bound for b_candidate
lower_b = max(required_max_b, min(b_sorted))
# Find the smallest b_candidate >= lower_b
idx = bisect.bisect_left(b_sorted, lower_b)
if idx < n:
b_candidate = b_sorted[idx]
ans = min(ans, abs(a_candidate - b_candidate))
# Find the largest b_candidate < lower_b
if idx > 0:
b_candidate = b_sorted[idx - 1]
if b_candidate >= lower_b:
ans = min(ans, abs(a_candidate - b_candidate))
results.append(ans)
for i, result in enumerate(results):
print(f"Case #{i+1}: {result}")
if name == "main": main()