P8592 "JROI-8" Traumatic Brain Injury 2.0 (Enhanced Version).

Background

Note the special time limit of this problem. [Normal Version](https://www.luogu.com.cn/problem/P8591).

Description

Given $n$ line segments, where the $i$-th segment is $[l_i, r_i]$, color each segment either red or black, such that: 1. Any two red segments do not intersect. 2. Any black segment intersects with **at least** one red segment. Minimize the total length of the red segments, and output this total length. The length of a segment $[l_i, r_i]$ is defined as $r_i - l_i$. Two segments $[l_i, r_i]$ and $[l_j, r_j]$ intersect **if and only if** there exists $k \in [l_i, r_i]$ and $k \in [l_j, r_j]$.

Input Format

The first line contains a positive integer $n$. The next $n$ lines each contain two integers $l_i, r_i$, separated by a space.

Output Format

Output one non-negative integer: the minimum possible total length of the red segments.

Explanation/Hint

**Constraints** | Test Point ID | $n \le$ | | :----------: | :----------: | | $1 \sim 10$ | $5 \times 10^5$ | For all testdata, $-10^9 \le l_i < r_i \le 10^9$. This problem uses bundled tests. Translated by ChatGPT 5