📌  相关文章
📜  教资会网络 | UGC-NET CS 2017 年 11 月 – III |问题 39(1)

📅  最后修改于: 2023-12-03 15:39:56.216000             🧑  作者: Mango

UGC-NET CS 2017 年 11 月 – III | Problem 39

该问题是计算机科学领域内的一个问题,需要程序员使用编程技能来解决。此问题的背景和细节如下:

Problem Description

Suppose you are given an undirected connected graph $G = (V, E)$ with weights $w(e)$ for all $e \in E$. A minimum spanning tree (MST) of $G$ is a subset of $E$ that connects all vertices in $V$ and has minimum total weight. Prim's algorithm and Kruskal's algorithm are two well-known algorithms for computing MSTs.

In this problem, you are given an implementation of Kruskal's algorithm (which finds the MST by sorting edges by weight and greedily adding them to the tree if they don't create a cycle), with one line of code removed. Your task is to fill in the missing line of code, such that the algorithm correctly computes the MST.

from queue import PriorityQueue
from typing import List, Tuple

def kruskal_mst(n: int, edges: List[Tuple[int,int,int]]) -> List[Tuple[int,int]]:
    uf = UnionFind(n)
    mst = []
    edges.sort(key=lambda e: e[2])
    for u, v, w in edges:
        if not uf.connected(u, v):
            uf.union(u, v)
            mst.append((u, v))
    return mst
Input

The input consists of an integer $1 \leq n \leq 10^4$, the number of vertices in the graph, followed by a list of edge tuples $(u, v, w)$ with $0 \leq u, v < n$ and $1 \leq w \leq 10^3$.

Output

The output is a list of edge tuples $(u,v)$ that form the edges of the MST, in the order they were added during the algorithm.

Example
Input:
5
(0, 1, 3)
(0, 2, 5)
(1, 2, 4)
(1, 3, 7)
(2, 3, 8)
(2, 4, 2)
(3, 4, 6)

Output:
[(2, 4), (0, 1), (0, 2), (3, 4)]
Solution

The missing line of code is the one that updates the Union-Find data structure with the newly-added edge. Specifically, we need to add the two vertices $u$ and $v$ to the same connected component, by calling the union() function of the Union-Find object. The updated code is shown below:

from queue import PriorityQueue
from typing import List, Tuple

def kruskal_mst(n: int, edges: List[Tuple[int,int,int]]) -> List[Tuple[int,int]]:
    uf = UnionFind(n)
    mst = []
    edges.sort(key=lambda e: e[2])
    for u, v, w in edges:
        if not uf.connected(u, v):
            uf.union(u, v)
            mst.append((u, v))
            # add the following line to update the Union-Find data structure
            uf.union(u, v)
    return mst

The corrected implementation calls the union(u, v) method of the UnionFind object twice, which ensures that both vertices are united in the same connected component. The running time of the corrected algorithm is $O(|E| \log |E|)$, which is the cost of sorting the edges.