103645: [Atcoder]ABC364 F - Range Connect MST

Memory Limit:256 MB Time Limit:2 S
Judge Style:Text Compare Creator:
Submit:5 Solved:0

Description

Score : $500$ points

Problem Statement

There is a graph with $N + Q$ vertices, numbered $1, 2, \ldots, N + Q$. Initially, the graph has no edges.

For this graph, perform the following operation for $i = 1, 2, \ldots, Q$ in order:

  • For each integer $j$ satisfying $L_i \leq j \leq R_i$, add an undirected edge with cost $C_i$ between vertices $N + i$ and $j$.

Determine if the graph is connected after all operations are completed. If it is connected, find the cost of a minimum spanning tree of the graph.

A minimum spanning tree is a spanning tree with the smallest possible cost, and the cost of a spanning tree is the sum of the costs of the edges used in the spanning tree.

Constraints

  • $1 \leq N, Q \leq 2 \times 10^5$
  • $1 \leq L_i \leq R_i \leq N$
  • $1 \leq C_i \leq 10^9$
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

$N$ $Q$
$L_1$ $R_1$ $C_1$
$L_2$ $R_2$ $C_2$
$\vdots$
$L_Q$ $R_Q$ $C_Q$

Output

If the graph is connected, print the cost of a minimum spanning tree. Otherwise, print $-1$.


Sample Input 1

4 3
1 2 2
1 3 4
2 4 5

Sample Output 1

22

The following edges form a minimum spanning tree:

  • An edge with cost $2$ connecting vertices $1$ and $5$
  • An edge with cost $2$ connecting vertices $2$ and $5$
  • An edge with cost $4$ connecting vertices $1$ and $6$
  • An edge with cost $4$ connecting vertices $3$ and $6$
  • An edge with cost $5$ connecting vertices $3$ and $7$
  • An edge with cost $5$ connecting vertices $4$ and $7$

Since $2 + 2 + 4 + 4 + 5 + 5 = 22$, print $22$.


Sample Input 2

6 2
1 2 10
4 6 10

Sample Output 2

-1

The graph is disconnected.


Sample Input 3

200000 4
1 200000 1000000000
1 200000 998244353
1 200000 999999999
1 200000 999999999

Sample Output 3

199651870599998

Output

得分:500分

问题陈述

有一个有$N + Q$个顶点的图,编号为$1, 2, \ldots, N + Q$。最初,该图没有边。

对于这个图,按顺序对$i = 1, 2, \ldots, Q$执行以下操作:

  • 对于每个满足$L_i \leq j \leq R_i$的整数$j$,在顶点$N + i$和$j$之间添加一条成本为$C_i$的无向边。

确定在所有操作完成后图是否连通。如果它是连通的,找到该图的最小生成树的成本。

最小生成树是具有可能的最小成本的生成树,生成树的成本是生成树中使用的边的成本之和。

约束条件

  • $1 \leq N, Q \leq 2 \times 10^5$
  • $1 \leq L_i \leq R_i \leq N$
  • $1 \leq C_i \leq 10^9$
  • 所有输入值都是整数。

输入

输入从标准输入以以下格式给出:

$N$ $Q$
$L_1$ $R_1$ $C_1$
$L_2$ $R_2$ $C_2$
$\vdots$
$L_Q$ $R_Q$ $C_Q$

输出

如果图是连通的,打印最小生成树的成本。否则,打印$-1$。


样本输入 1

4 3
1 2 2
1 3 4
2 4 5

样本输出 1

22

以下边构成了一个最小生成树:

  • 一条成本为$2$的边,连接顶点$1$和$5$
  • 一条成本为$2$的边,连接顶点$2$和$5$
  • 一条成本为$4$的边,连接顶点$1$和$6$
  • 一条成本为$4$的边,连接顶点$3$和$6$
  • 一条成本为$5$的边,连接顶点$3$和$7$
  • 一条成本为$5$的边,连接顶点$4$和$7$

由于$2 + 2 + 4 + 4 + 5 + 5 = 22$,打印$22$。


样本输入 2

6 2
1 2 10
4 6 10

样本输出 2

-1

图是断开的。


样本输入 3

200000 4
1 200000 1000000000
1 200000 998244353
1 200000 999999999
1 200000 999999999

样本输出 3

199651870599998

加入题单

上一题 下一题 算法标签: