#include #include #include #include #include #include #include int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; std::vector> lr(n); for (auto& [l, r] : lr) std::cin >> l >> r; std::ranges::sort(lr); int k = 0; for (int i = 0; i < n; ++i) { k = std::max(k, lr[i].first - i); } for (auto& [l, r] : lr) { l = std::max(l, k); if (l > r) { std::cout << -1 << std::endl; return 0; } l -= k, r -= k; } std::vector> bucket(n); for (int i = 0; i < n; ++i) { auto [l, r] = lr[i]; bucket[l].push_back(r); } std::priority_queue, std::greater> pq; for (int l = 0; l < n; ++l) { for (int r : bucket[l]) pq.push(r); assert(pq.size()); if (pq.top() < l) { std::cout << -1 << std::endl; return 0; } pq.pop(); } std::cout << k - 1 << std::endl; }