#abc364f. F - Range Connect MST

F - Range Connect MST

Score : 500500 points

问题陈述

有一个图,包含 N+QN + Q 个顶点,编号为 1,2,,N+Q1, 2, \ldots, N + Q。最初,图中没有边。

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

  • 对于满足 LijRiL_i \leq j \leq R_i 的每个整数 jj,在顶点 N+iN + ijj 之间添加一条成本为 CiC_i 的无向边。

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

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

以上为大语言模型 kimi 翻译,仅供参考。

Problem Statement

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

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

  • For each integer jj satisfying LijRiL_i \leq j \leq R_i, add an undirected edge with cost CiC_i between vertices N+iN + i and jj.

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

  • 1N,Q2×1051 \leq N, Q \leq 2 \times 10^5
  • 1LiRiN1 \leq L_i \leq R_i \leq N
  • 1Ci1091 \leq C_i \leq 10^9
  • All input values are integers.

Input

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

NN QQ

L1L_1 R1R_1 C1C_1

L2L_2 R2R_2 C2C_2

\vdots

LQL_Q RQR_Q CQC_Q

Output

If the graph is connected, print the cost of a minimum spanning tree. Otherwise, print 1-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 22 connecting vertices 11 and 55
  • An edge with cost 22 connecting vertices 22 and 55
  • An edge with cost 44 connecting vertices 11 and 66
  • An edge with cost 44 connecting vertices 33 and 66
  • An edge with cost 55 connecting vertices 33 and 77
  • An edge with cost 55 connecting vertices 44 and 77

Since 2+2+4+4+5+5=222 + 2 + 4 + 4 + 5 + 5 = 22, print 2222.

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