CF BUDDY
← Problems·

1801B · Buying gifts

1800 · data structures, greedy, sortings

Problem: There are nn departments in the mall, each of which has exactly two stores. For convenience, we number the departments with integers from 11 to nn. It is known that gifts in the first store of the ii department cost aia_i rubles, and in the second store of the ii department — bib_i rubles.

Entering the mall, Sasha will visit each of the nn departments of the mall, and in each department, he will enter exactly one store. When Sasha gets into the ii-th department, he will perform exactly one of two actions:

  1. Buy a gift for the first friend, spending aia_i rubles on it.
  2. Buy a gift for the second friend, spending bib_i rubles on it.

Sasha is going to buy at least one gift for each friend. Moreover, he wants to pick up gifts in such a way that the price difference of the most expensive gifts bought for friends is as small as possible so that no one is offended.

More formally: let m1m_1  be the maximum price of a gift bought to the first friend, and m2m_2  be the maximum price of a gift bought to the second friend. Sasha wants to choose gifts in such a way as to minimize the value of m1m2\lvert m_1 - m_2 \rvert.

Input Format: Each test contains multiple test cases. The first line contains the number of test cases tt (1t10001 \le t \le 1\,000). The description of the test cases follows.

The first line of each test case contains a single integer nn (2n5000002 \le n \le 500\,000) — the number of departments in the mall.

Each of the following nn lines of each test case contains two integers aia_i and bib_i (0ai,bi1090 \le a_i, b_i \le 10^9) — the prices of gifts in the first and second store of the ii department, respectively.

It is guaranteed that the sum of nn over all test cases does not exceed 500000500\,000.

Output Format: Print one integer — the minimum price difference of the most expensive gifts bought to friends.

Note: In the first test case, Sasha has two possible options: buy a gift for the first friend in the first department, and the second friend  — in the second department, or vice versa. In the first case, m1=m2=1m_1 = m_2 = 1, and in the second case — m1=m2=2m_1 = m_2 = 2. In both cases, the answer is 00. In the second test case, you can buy gifts for the first friend in the 22, 44 and 55 departments, and for the second friend  — in the 11 and 33 departments.So m1=max(2,4,2)=4m_1 = \max(2, 4, 2) = 4, m2=max(5,3)=5m_2 = \max(5, 3) = 5. The answer is 45=1\lvert 4 - 5 \rvert = 1.

Sample Cases

Case 1

Input

2
2
1 2
2 1
5
1 5
2 7
3 3
4 10
2 5

Output

0
1

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback