221902285-Algorithm Lab Report 6
221902285-Algorithm Lab Report 6
Student Details
Name ID
2. OBJECTIVES/AIM
The objective of the Second-Best Minimum Spanning Tree problem is to find the spanning
tree of a weighted graph with the second-smallest total weight. This means finding a tree
that connects all the vertices in the graph while minimizing the sum of the edge weights,
but without being the absolute minimum.
3. IMPLEMENTATION
Question 1:
Write a program to find the second-best MST.
Code:
package MST;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
if (find(source) != find(destination)) {
System.out.println(source + " " + destination + " " + weight);
FirstMst.add(new Edge(source, destination, weight));
cost += weight;
union(source, destination);
}
}
System.out.println("Cost of 1st MST: " + cost);
cost = 0;
SecondBestMst.clear();
if (find(source) != find(destination)) {
SecondBestMst.add(new Edge(source, destination, weight));
cost += weight;
union(source, destination);
}
}
try {
Scanner sn = new Scanner(file);
if (sn.hasNextLine()) {
v = sn.nextInt();
}
if (sn.hasNextLine()) {
e = sn.nextInt();
}
while (sn.hasNextLine()) {
int source = 0, des = 0, weight = 0;
if (sn.hasNextInt()) {
source = sn.nextInt();
}
if (sn.hasNextInt()) {
des = sn.nextInt();
}
if (sn.hasNextInt()) {
weight = sn.nextInt();
}
edges.add(new Edge(source, des, weight));
}
sn.close();
} catch (FileNotFoundException ex) {
System.out.println("File Not Found");
}
}
}
5. TEST RESULT / OUTPUT
The Graph:
Input in “tree.txt”
5
7
0 1 20
0 2 3
1 3 2
1 4 6
2 3 1
2 4 10
3 4 4
Output:
6. Discussion
Exploring the second-best minimum spanning tree introduces an additional layer of
complexity to classic MST algorithms. The adaptation involves careful consideration of
alternative edge choices while maintaining the efficiency and correctness of the algorithm.
The concept is particularly relevant in scenarios where redundancy and resilience are
critical considerations in network design and optimization.