DSA 部分簡單

克魯斯卡爾

“Kruskal”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 kruskal_mst(V, edges),它接受頂點數 V 和表示為元組 (u, v, w) 的邊列表 edges,其中 uv 是頂點,w 是邊權重。尋找最小生成樹 (MST),並使用 Kruskal 演算法傳回 MST 中包含的邊的權重總和。

約束條件
  • 1 <= V <= 500
  • 0 <= len(edges) <= 1000

範例

Example 1
Input
V = 4, edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)]
Output
19
Explanation

MST contains edges (2,3) wt 4, (0,3) wt 5, and (0,1) wt 10. Total weight = 19.

Need a Hint?
考慮使用特定於圖的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。