Problem - B - Codeforces
#include <iostream>
#include <bits/stdc++.h>
#include <cstring>
#include <vector>
#include <algorithm>
#define x first
#define y second
#define fu(i,a,b) for(int i=a;i<=b;i ++ )
#define fd(i,a,b) for(int i=a;i>=b;i -- )
#define endl '\n'
#define ms(x,y) memset(x,y,sizeof x)
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
typedef pair<double,int> PDI;
typedef pair<char,int> PCI;
typedef pair<string,int> PSI;
typedef pair<int,string> PIS;
typedef pair<LL,LL> PLL;
//typedef __int128 i128;
typedef unsigned long long ULL;
const int N = 1e5+ 10,M = 1e5 + 10,INF = 0x3f3f3f3f ;
const int mod = 1e9;
const double eps = 1e-8;
int n;
// 第一个人只能从 第一个商店买东西 。。
inline void solve()
{
cin >> n;
int ans = 1e9;
vector<PII>a(2 * n );
fu(i,0,n-1)
{
int x,y;cin >> x >> y ;
a[2 * i ] = {x,2 * i};
a[2 *i + 1 ] = {y,2 * i+1};
}
// 第二维的奇偶性是 对应两个人,偶数->第一个人,奇数 -> 第二个人
sort(a.begin(),a.end());
PII mx[2][2];
// i偶数->第一个人,奇数 -> 第二个人
// j 当前的 0 最大值 1 次大值
ms(mx,-1);
vector<bool> st(n);
int bad = n;
for(auto t : a)
{
int u = t.y % 2 ;
// 当前是第一个商店还第二个商店
mx[u][1] = mx[u][0];
mx[u][0] = t;
bad -= !st[t.y/2];
// 如果当前部门还没有买东西 就-1
st[t.y/ 2 ] = 1; // 当前部门已经选择了
for(int i=0 ;i < 2; i++ )
if(!bad && mx[!u][i].y != -1 && mx[!u][i].y != (t.y ^ 1 ) )
// 当前 已经考虑完所有部门 且当前人的 另一个人 最大值或次大值已经有商店的选择了,
//且选择的不是和当前这个人同一个商店
ans = min(ans,t.x - mx[!u][i].x);
// 当前这个人的 值 和 另一个人的最大值和次大值的差取最小
}
cout << ans << endl;
}
signed main()
{
// freopen("1.txt","w",stdout);
ios
int t=1;
cin>>t;
int now = 1;
while(t -- )
{
// cout<<"Case ";
// cout<<"Case #";
// cout<< now ++ <<": ";
solve();
}
return 0;
}