Minimum Spanning Tree (Kruskal's Algorithm)
Xem dạng PDF
Gửi bài giải
Điểm:
100,00
Giới hạn thời gian:
2.0s
Giới hạn bộ nhớ:
256M
Tác giả:
Dạng bài
Ngôn ngữ cho phép
Python
Problem Statement
Given a weighted undirected graph with n nodes and m edges, compute the total weight of the Minimum Spanning Tree (MST) using Kruskal's algorithm.
Algorithm:
- Sort edges by weight (ascending).
- Use Union-Find to greedily add edges: include an edge if it connects two different components.
- Stop when
n-1edges have been added. - If fewer than
n-1edges can be added, the graph is disconnected — output"DISCONNECTED".
Function signature:
def mst_weight(n: int, edges: list) -> int | str:
# edges: list of (u, v, weight)
# returns total MST weight, or "DISCONNECTED" if no spanning tree exists
Input Format
Line 1: n m — number of nodes and edges
Lines 2..m+1: u v w — edge from u to v with weight w
Output Format
One line: the total MST weight (integer), or DISCONNECTED
Example
Input:
4 5
0 1 10
0 2 6
0 3 5
1 3 15
2 3 4
Output:
19
Notes
- Chosen edges:
(2,3,4),(0,3,5),(0,2,6)— wait, that forms a cycle. Correct:(2,3,4),(0,3,5),(0,1,10)= 19. - Use Union-Find with path compression and union by rank for efficiency.
- Nodes are 0-indexed.
Bình luận