#include using namespace std; //* ATCODER #include using namespace atcoder; typedef modint998244353 mint; //*/ /* BOOST MULTIPRECISION #include using namespace boost::multiprecision; //*/ typedef long long ll; #define rep(i, s, n) for (int i = (int)(s); i < (int)(n); i++) #define rrep(i, s, n) for (int i = (int)(n)-1; i >= (int)(s); i--) template bool chmin(T &a, const T &b) { if (a <= b) return false; a = b; return true; } template bool chmax(T &a, const T &b) { if (a >= b) return false; a = b; return true; } template T max(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmax(ret, a[i]); return ret; } template T min(vector &a){ assert(!a.empty()); T ret = a[0]; for (int i=0; i<(int)a.size(); i++) chmin(ret, a[i]); return ret; } template T sum(vector &a){ T ret = 0; for (int i=0; i<(int)a.size(); i++) ret += a[i]; return ret; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector l(n), r(n); rep(i,0,n){ cin >> l[i] >> r[i]; } vector tar = r; sort(tar.begin(), tar.end()); auto check_up = [&](ll t) -> bool { vector g = tar; rep(i,0,n){ g[i] -= t; } rep(i,1,n+1){ if (i > g[i-1]){ return false; } } return true; }; auto check_real = [&](ll t) -> bool { vector bucket(n+1, vector(0)); rep(i,0,n){ if (max((ll)1, l[i]-t) > n) return false; bucket[max((ll)1, l[i]-t)].push_back(r[i]-t); } priority_queue,greater> pq; rep(i,1,n+1){ for (ll j: bucket[i]){ pq.push(j); } if(!pq.empty()){ ll a = pq.top(); if (i > a){ return false; } pq.pop(); }else{ return false; } } return true; }; ll ub_upper = 1e12; // NG ll lb_upper = -1e12; // OK while(ub_upper - lb_upper > 1){ ll t = (ub_upper - lb_upper) / 2 + lb_upper; if (check_up(t)) lb_upper = t; else ub_upper = t; } if (!check_real(lb_upper)){ cout << 0 << '\n'; return 0; } ll ub_lower = lb_upper; // OK ll lb_lower = -1e12; // NG while(ub_lower - lb_lower > 1){ ll t = (ub_lower - lb_lower) / 2 + lb_lower; if (check_real(t)) ub_lower = t; else lb_lower = t; } cout << ub_upper - ub_lower << '\n'; }