You are given a weighted tree with N nodes and N-1 edges.
E is defined as a summation F(i,j) for all 1 <= i < j <= N. Also, F(i,j) is equal to the maximum value of the edge that is present on the simple path between node i and j.
You are required to determine the value of E.
Example
Assumption
Approach
Function Description
Complete the solve() function. This function takes the following 2 parameters and returns the value of E.
Input Format:
Note: This is the input format you must use to provide custom input available above the Compile and Test button.
Output Format:
Print the required value of E.
Constraint:
Sample Input
3
1 2 10
1 3 2
Sample Output
22
Explanation
Given
Approach
The problem becomes much simpler if we try to change our perspective. Rather than trying to find the maximum edge for all paths, lets try to find the number of paths for which the maximum weighted edge is a particular edge. If we can find out the number of paths for each edge, then we can find the answer to the problem easily.
Lets try to add the edges in the order of increasing values. Now by the property of a tree, every edge connects two connected components such that there is no path that starts from one of the component and goes to the other without traversing this edge. Also since we are adding the edges in increasing order, the value of all the edges present in the tree so far is less than or equal to the value of the current edge. Thus, we can say that the current edge will be the maximum weighted edge for all the paths that start from one of the component and goes to the other. The number of such paths will simply be the product of the sizes of components involved (You need to pick exactly one node from each of the components). We can thus add the contribution of this edge into the ans. This technique is used in a wide variety of problems and is popularly known as Contribution Technique.
Based on the above analysis, we can solve the problem simply by using a DSU(Disjoint Set Union). The steps involved are:
W*|A|*|B|
, where W is the weight of the current edge and |A| and |B| are the sizes of the components A and B respectively.class DSU: //DSU implemntation
parent = [i for i in range(1,N)]
size = [1]*N
find(x): //find(x) returns the representative element of the set containing x
return parent[x] = (parent[x] == x) ? x : find(parent[x])
merge(a,b): //We return the product of sizes of components involved in the merge operation
a = find(a)
b = find(b)
ret = size[a] * size[b]
if(size[b] > size[a]) swap(a,b)
size[a] += size[b]
parent[b] = a
return ret
solve(N, Edges)
d = DSU(N)
Edges.sort(key = weight) //sort the edges w.r.t their weight
ans = 0
for edge in edges: //add the edges in increasing order of their weight
ans += edge.weight * d.merge(edge.a, edge.b) // add the contribution of current edge into the ans
return ans