#abc352e. E - Clique Connect

E - Clique Connect

Score: 450450 points

问题陈述

给定一个加权无向图 GG,包含 NN 个顶点,编号为 11NN。最初,GG 没有边。

你将执行 MM 次操作以向 GG 添加边。第 ii 次操作 (1iM)(1 \leq i \leq M) 如下:

  • 给定一个顶点子集 Si={Ai,1,Ai,2,,Ai,Ki}S_i=\lbrace A_{i,1},A_{i,2},\dots,A_{i,K_i}\rbrace,包含 KiK_i 个顶点。对于每一对 u,vu, v,满足 u,vSiu, v \in S_iu<vu < v,在顶点 uuvv 之间添加一条权重为 CiC_i 的边。

执行完所有 MM 次操作后,确定 GG 是否连通。如果连通,找出 GG 的最小生成树中边的总权重。

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

Problem Statement

You are given a weighted undirected graph GG with NN vertices, numbered 11 to NN. Initially, GG has no edges.

You will perform MM operations to add edges to GG. The ii-th operation (1iM)(1 \leq i \leq M) is as follows:

  • You are given a subset of vertices Si={Ai,1,Ai,2,,Ai,Ki}S_i=\lbrace A_{i,1},A_{i,2},\dots,A_{i,K_i}\rbrace consisting of KiK_i vertices. For every pair u,vu, v such that u,vSiu, v \in S_i and u<vu < v, add an edge between vertices uu and vv with weight CiC_i.

After performing all MM operations, determine whether GG is connected. If it is, find the total weight of the edges in a minimum spanning tree of GG.

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • 1M2×1051 \leq M \leq 2 \times 10^5
  • 2KiN2 \leq K_i \leq N
  • i=1MKi4×105\sum_{i=1}^{M} K_i \leq 4 \times 10^5
  • $1 \leq A_{i,1} < A_{i,2} < \dots < A_{i,K_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 MM

K1K_1 C1C_1

A1,1A_{1,1} A1,2A_{1,2} \dots A1,K1A_{1,K_1}

K2K_2 C2C_2

A2,1A_{2,1} A2,2A_{2,2} \dots A2,K2A_{2,K_2}

\vdots

KMK_M CMC_M

AM,1A_{M,1} AM,2A_{M,2} \dots AM,KMA_{M,K_M}

Output

If GG is not connected after all MM operations, print -1. If GG is connected, print the total weight of the edges in a minimum spanning tree of GG.

Sample Input 1

4 3
3 3
1 2 3
2 2
1 2
3 4
1 3 4

Sample Output 1

9

The left diagram shows GG after all MM operations, and the right diagram shows a minimum spanning tree of GG (the numbers next to the edges indicate their weights).

The total weight of the edges in the minimum spanning tree is 3+2+4=93 + 2 + 4 = 9.

Sample Input 2

3 2
2 1
1 2
2 1
1 2

Sample Output 2

-1

GG is not connected even after all MM operations.

Sample Input 3

10 5
6 158260522
1 3 6 8 9 10
10 877914575
1 2 3 4 5 6 7 8 9 10
4 602436426
2 6 7 9
6 24979445
2 3 4 5 8 10
4 861648772
2 4 8 9

Sample Output 3

1202115217