Codeforces Round 1049 (Div. 2)
D
A Cruel Segment's Thesis
Codeforces
2000
原题
← CE1 →
翻译中…

You are given $n$ segments on a number line. The $i$-th segment is represented as $[l_i, r_i]$. Initially, all the segments are unmarked.

翻译中…

You perform the following operation repeatedly until there are no unmarked segments left:

翻译中…
  1. In the $k$-th operation, if there are at least two unmarked segments, choose any two unmarked segments $[l_i, r_i]$ and $[l_j, r_j]$, mark both of them, and add a new marked segment $[x_k, y_k]$ satisfying the following conditions:
  • $l_i \leq x_k \leq r_i$,
    • $l_j \leq y_k \leq r_j$,
    • $x_k \leq y_k$.
  1. If there is exactly one unmarked segment remaining, mark it.
翻译中…

Your task is to determine the maximum possible sum of lengths of all the marked segments at the end of the process. Note that the length of a segment $([l,r])$ is $r-l$.

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.

翻译中…

The first line of each test case contains a single integer $n$ ($1 \leq n \leq 2 \cdot 10^5$) — the number of segments.

翻译中…

Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($1 \leq l_i \leq r_i \leq 10^9$) — the $i$-th segment.

翻译中…

It is guaranteed that the sum of $n$ across all test cases does not exceed $2 \cdot 10^5$.

翻译中…

Output

翻译中…

For each test case, print a single integer — the maximum possible total length of all marked segments at the end of the process.

翻译中…

Note

翻译中…

In the first test case, we choose the given two segments and make the new segment $[1, 10^9]$.

翻译中…

In the second test case, we choose the segments $[1, 10]$ and $[2, 15]$ and make the new segment $[1,15]$. Now, $[3, 9]$ is the only segment that is left unmarked, and it will be marked in the next step.

翻译中…

样例

Input #1
4
2
1 1000000000
1 1000000000
3
1 10
2 15
3 9
5
1 11
2 7
15 20
1 3
11 15
1
1000000000 1000000000
Output #1
2999999997
42
59
0
InputCopy OutputCopy
题目信息
题号
2140D
时间限制
2 s
内存限制
256 MB
标签
数据结构
贪心
排序

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。