Given a tree with N vertices and N-1 Edges. Let’s define a function F(a, b) which is equal to the minimum edge weight in the path between node a & b. The task is to calculate the product of all such F(a, b). Here a&b are unordered pairs and a!=b.
So, basically, we need to find the value of:
In the input, we will be given the value of N and then N-1 lines follow. Each line contains 3 integers u, v, w denoting edge between node u and v and it’s weight w. Since the product will be very large, output it modulo 10^9+7.
Input : N = 4 1 2 1 1 3 3 4 3 2 Output : 12 Given tree is: 1 (1)/ \(3) 2 3 \(2) 4 We will calculate the minimum edge weight between all the pairs: F(1, 2) = 1 F(2, 3) = 1 F(1, 3) = 3 F(2, 4) = 1 F(1, 4) = 2 F(3, 4) = 2 Product of all F(i, j) = 1*3*2*1*1*2 = 12 mod (10^9 +7) =12 Input : N = 5 1 2 1 1 3 3 4 3 2 1 5 4 Output : 288
If we observe carefully then we will see that if there is a set of nodes in which minimum edge weight is w and if we add a node to this set that connects the node with the whole set by an edge of weight W such that W<w then path formed between recently added node to all nodes present in the set will have minimum weight W.
So, here we can apply Disjoint-Set Union concept to solve the problem.
First, sort the data structure according to decreasing weight. Initially assign all nodes as a single set. Now when we merge two sets then do the following:-
Product=(present weight)^(size of set1*size of set2).
We will multiply this product value for all edges of the tree.
Below is the implementation of the above approach:
Time Complexity : O(N*logN)
- Remove all outgoing edges except edge with minimum weight
- Count number of paths whose weight is exactly X and has at-least one edge of weight M
- Find the weight of the minimum spanning tree
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Minimum Product Spanning Tree
- Sum and Product of maximum and minimum element in Binary Tree
- Sum and Product of minimum and maximum element of Binary Search Tree
- Minimum edge reversals to make a root
- Number of Paths of Weight W in a K-ary tree
- Count the nodes in the given tree whose weight is even
- Maximum edge removal from tree to make even forest
- Tree, Back, Edge and Cross Edges in DFS of Graph
- Count the nodes in the given tree whose weight is even parity
- Count the nodes of the given tree whose weight has X as a factor
- Count the nodes in the given tree whose sum of digits of weight is odd
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.