PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GD0000225. Cây khung nhỏ nhất (Minimum Spanning Tree)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Cây khung nhỏ nhất (Minimum Spanning Tree)

Minimum Spanning Tree

Source: Kattis

Version: Phuoc Hung OJ Extended

Problem Statement

Given an undirected weighted graph with nn vertices numbered from 00 to n−1n-1 and mm edges, find a minimum spanning tree: n−1n-1 edges connecting every vertex without cycles and with minimum total weight.

If the graph is disconnected, no spanning tree exists. Any minimum spanning tree is accepted, but output its edges in lexicographic order after writing the smaller endpoint first.

Input

  • The first line contains n,mn,m.
  • Each of the next mm lines contains u,v,wu,v,w describing one undirected weighted edge. Vertices are zero-indexed.

Output

If the graph is disconnected, print Impossible.

Otherwise print the minimum total weight on the first line, followed by n−1n-1 selected edges, one per line. Each edge has its smaller endpoint first, and the edge pairs must be lexicographically sorted.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le 20; 0≤m≤5⋅1040\le m\le 5\cdot 10^4; 0≤u,v<n, u≠v0\le u,v<n,\ u\ne v; −104≤w≤104-10^4\le w\le 10^4; m≤n(n−1)/2m\le n(n-1)/2; không có cạnh trùng.
  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 0≤m≤5⋅1040\le m\le 5\cdot 10^4; 0≤u,v<n, u≠v0\le u,v<n,\ u\ne v; −104≤w≤104-10^4\le w\le 10^4; m≤n(n−1)/2m\le n(n-1)/2; không có cạnh trùng.
  • Subtask 3 (50 points): 1≤n≤100001\le n\le 10000; 0≤m≤5⋅1040\le m\le 5\cdot 10^4; 0≤u,v<n, u≠v0\le u,v<n,\ u\ne v; −104≤w≤104-10^4\le w\le 10^4; m≤n(n−1)/2m\le n(n-1)/2; không có cạnh trùng.

Examples

Input

4 5
0 1 2
0 2 3
0 3 7
1 2 1
2 3 4

Output

7
0 1
1 2
2 3

Explanation

Select edges (1,2)(1,2) of weight 11, (0,1)(0,1) of weight 22, and (2,3)(2,3) of weight 44, totaling 77. They connect all four vertices without cycles. Print them sorted: (0,1),(1,2),(2,3)(0,1),(1,2),(2,3).