Written on: October 21, 2023
Introduction
The Minimum Spanning Tree (MST) problem, which frequently appears in programming tests, is one of the important concepts in graph theory. A minimum spanning tree refers to a tree structure that includes all vertices of a graph while minimizing the sum of weights.
In this article, we will explore an algorithm for finding the minimum spanning tree using the Kotlin language and learn how to apply the theory through related problem-solving examples.
Basic Concepts
Graph
A graph is a data structure composed of vertices and edges. Vertices represent nodes, and edges represent the connections between those nodes.
Graphs can be classified into directed and undirected graphs, and if edges have weights, they are called weighted graphs.
Minimum Spanning Tree (MST)
A minimum spanning tree is a tree with the minimum sum of weights among the subgraphs that connect all vertices in a weighted graph.
Prim’s algorithm and Kruskal’s algorithm are commonly used algorithms for finding the MST.
Problem Description
Problem Definition
You are given an undirected graph and the weights of its edges. Write a program to find the minimum spanning tree that includes all vertices of this graph and outputs the sum of its weights.
Input Format
- The first line contains the number of vertices
V
and the number of edgesE
. (1 ≤ V ≤ 1000
,1 ≤ E ≤ 10000
) - The next
E
lines contain the two vertices of each edge and the weight.
Output Format
Output the sum of the weights of the minimum spanning tree.
Problem Solving Process
Approach Using Kruskal’s Algorithm
Kruskal’s algorithm involves sorting the edges based on their weights and then selecting edges that do not form cycles to construct the minimum spanning tree.
This algorithm sorts the edges of the given graph and uses a union-find data structure to check for cycles.
The process proceeds through the following steps.
- Sort edges: Sort all edges in ascending order based on their weights.
- Initialize union-find: Initialize each vertex as an independent set.
- Construct the minimum spanning tree: Traverse the sorted edges and add the edge to the MST if it does not form a cycle.
Kotlin Implementation
Code Example
class Edge(val u: Int, val v: Int, val weight: Int): Comparable {
override fun compareTo(other: Edge) = this.weight - other.weight
}
class DisjointSet(val size: Int) {
private val parent = IntArray(size) { it }
private val rank = IntArray(size) { 0 }
fun find(x: Int): Int {
if (parent[x] != x) {
parent[x] = find(parent[x])
}
return parent[x]
}
fun union(x: Int, y: Int): Boolean {
val rootX = find(x)
val rootY = find(y)
if (rootX == rootY) return false
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY
} else {
parent[rootY] = rootX
rank[rootX]++
}
return true
}
}
fun kruskal(vertices: Int, edges: List): Int {
val disjointSet = DisjointSet(vertices)
val sortedEdges = edges.sorted()
var totalWeight = 0
for (edge in sortedEdges) {
if (disjointSet.union(edge.u, edge.v)) {
totalWeight += edge.weight
}
}
return totalWeight
}
fun main() {
val reader = System.`in`.bufferedReader()
val (V, E) = reader.readLine().split(" ").map { it.toInt() }
val edges = mutableListOf()
for (i in 0 until E) {
val (u, v, weight) = reader.readLine().split(" ").map { it.toInt() }
edges.add(Edge(u - 1, v - 1, weight))
}
val result = kruskal(V, edges)
println(result)
}
Code Explanation
The above code finds the minimum spanning tree based on Kruskal’s algorithm.
The Edge class stores edge information, and the DisjointSet class provides functionality to find the representative of sets and merge two sets based on the union-find algorithm.
kruskal function uses the input number of vertices and the edge list to sort all edges based on their weights.
It then traverses the sorted edges, adding an edge to the MST only if no cycle occurs.
Finally, it returns the total weight of the MST.
Test Cases
Example Input
5 6
1 2 3
1 3 4
2 3 1
2 4 6
3 4 5
4 5 2
Example Output
10
Explanation
The given graph consists of 5 vertices and 6 edges, and the minimum spanning tree consists of edges with weights 1, 2, 3, and 4, totaling a weight of 10.
Conclusion
In this article, we implemented an algorithm to find the minimum spanning tree using Kotlin and solved a problem to enhance our understanding of the process.
The minimum spanning tree is an important concept that can be applied to various real-world problems, and there are other approaches like Prim’s algorithm in addition to Kruskal’s algorithm.
Utilizing these algorithms enables efficient solutions to graph problems.
We will continue to introduce various algorithms to help you achieve successful results in coding tests.