![]() |
VOOZH | about |
Given a connected and undirected graph, a spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. A minimum product spanning tree for a weighted, connected, and undirected graph is a spanning tree with a weight product less than or equal to the weight product of every other spanning tree. The weight product of a spanning tree is the product of weights corresponding to each edge of the spanning tree. All weights of the given graph will be positive for simplicity.
Examples:
Minimum Product that we can obtain is 180 for above graph by choosing edges 0-1, 1-2, 0-3 and 1-4
This problem can be solved using standard minimum spanning tree algorithms like Kruskal (https://www.geeksforgeeks.org/dsa/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/)and primβs algorithm, but we need to modify our graph to use these algorithms. Minimum spanning tree algorithms tries to minimize the total sum of weights, here we need to minimize the total product of weights. We can use the property of logarithms to overcome this problem.
As we know,
log(w1* w2 * w3 * β¦. * wN) = log(w1) + log(w2) + log(w3) β¦.. + log(wN)
We can replace each weight of the graph by its log value, then we apply any minimum spanning tree algorithm which will try to minimize the sum of log(wi) which in turn minimizes the weight product.
For example graph, the steps are shown below diagram,
In the below code first, we have constructed the log graph from the given input graph, then that graph is given as input to primβs MST algorithm, which will minimize the total sum of weights of the tree. Since weights of the modified graph are logarithms of the actual input graph, we actually minimize the product of weights of the spanning tree.
Output:
Edge Weight 0 - 1 2 1 - 2 3 0 - 3 6 1 - 4 5 Minimum Obtainable product is 180
The time complexity of this algorithm is O(V2) as there are two nested for loops which iterate over all the vertices.
The space complexity of this algorithm is O(V2), as we are using a 2-D array of size V x V to store the input graph.