Maximum Weight Edge Sum

You are given a weighted tree A, having N nodes.

The score of vertex pair vi and vj is the maximum weight edge on the simple path between them.

Find and return the sum of scores of all unordered pairs of vertices.

As the sum of scores can be huge, return the answer modulo 109 + 7.


Input Format:

The first and the only argument of input contains a matrix A, of size (N - 1) x 3.
	=> The number of nodes in the tree is N.
	=> Here, A[i][0] and A[i][1] are connected by an edge of weight A[i][2].

Output Format:

Return an integer representing the sum of scores of all unordered pairs of vertices.

Constraints:

1 <= N <= 1e5
1 <= A[i][0], A[i][1] <= N
1 <= A[i][2] <= 1e3

Examples:

Input 1:
	A = [	[1, 2, 10],
			[3, 2, 10]	]

Output 1:
	30

Explanation 2:
	The given tree has 3 nodes.

	Vertex Pair - Score

	(1, 2) - 10
	(1, 3) - 10
	(2, 3) - 10

	Total sum = 10 + 10 + 10 = 30

Input 2:
	A = [	[1, 4, 7],
			[4, 5, 8],
			[2, 3, 6],
			[3, 4, 1]	]

Output 2:
	66

Explanation 2:
	The given tree has 5 nodes.

	Vertex Pair - Score
	(1, 2) - 7
	(1, 3) - 7
	(1, 4) - 7
	(1, 5) - 8
	(2, 3) - 6
	(2, 4) - 6
	(2, 5) - 8
	(3, 4) - 1
	(3, 5) - 8
	(4, 5) - 8

	Total sum = 7 + 7 + 7 + 8 + 6 + 6 + 8 + 1 + 8 + 8 = 66
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified. Still have a doubt? Checkout Sample Codes for more details.
Start solving Maximum Weight Edge Sum on Interview Code Editor
Sign Up
to access hints and editorial solutions for Maximum Weight Edge Sum

Discussion


Loading...
Click here to start solving coding interview questions