Codeforces Round 949 (Div. 2)
E
Turtle and Intersected Segments
Codeforces
2600
原题
← DF →
翻译中…

Turtle just received $n$ segments and a sequence $a_1, a_2, \ldots, a_n$. The $i$-th segment is $[l_i, r_i]$.

翻译中…

Turtle will create an undirected graph $G$. If segment $i$ and segment $j$ intersect, then Turtle will add an undirected edge between $i$ and $j$ with a weight of $|a_i - a_j|$, for every $i \ne j$.

翻译中…

Turtle wants you to calculate the sum of the weights of the edges of the minimum spanning tree of the graph $G$, or report that the graph $G$ has no spanning tree.

翻译中…

We say two segments $[l_1, r_1]$ and $[l_2, r_2]$ intersect if and only if $\max(l_1, l_2) \le \min(r_1, r_2)$.

翻译中…

Input

翻译中…

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

翻译中…

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

翻译中…

The $i$-th of the following $n$ lines contains three integers $l_i, r_i, a_i$ ($1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$) — the $i$-th segment and the $i$-th element of the sequence.

翻译中…

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

翻译中…

Output

翻译中…

For each test case, output a single integer — the sum of the weights of the edges of the minimum spanning tree of the graph $G$. If the graph $G$ has no spanning tree, output $-1$.

翻译中…

Note

翻译中…

In the first test case, the graph $G$ is as follows:

翻译中…

image

翻译中…

One of the minimum spanning trees of $G$ is as follows:

翻译中…

image

翻译中…

The sum of the weights of the edges of the minimum spanning tree is $9$.

翻译中…

In the second test case, the graph $G$ is as follows:

翻译中…

image

翻译中…

$G$ is already a tree, and the sum of the weights of the tree is $13$.

翻译中…

In the third test case, the graph $G$ is as follows:

翻译中…

image

翻译中…

In the fourth test case, the graph $G$ is as follows:

翻译中…

image

翻译中…

It's easy to see that $G$ is not connected, so $G$ has no spanning tree.

翻译中…

样例

Input #1
4
5
1 7 3
2 4 6
3 5 5
6 7 9
3 4 4
5
2 7 3
1 3 6
4 5 5
6 7 9
1 1 4
4
1 4 3
1 2 1
3 4 5
1 4 4
3
1 3 1
2 3 3
4 5 8
Output #1
9
13
4
-1
InputCopy OutputCopy
题目信息
题号
1981E
时间限制
5 s
内存限制
512 MB
标签
数据结构
并查集
图论
贪心

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