eolymp
bolt
Try our new interface for solving problems
Problems

Sum of distances

Sum of distances

A weighted tree with $n$ vertices and $n - 1$ edges is given. The distance between vertices $u$ and $v$ is defined as the weight of the smallest edge on the path between $u$ and $v$. Find the sum of distances between all pairs of vertices in the tree. \InputFile The first line contains the number of vertices $n~(2 \le n \le 10^5)$ in the graph. The next $n - 1$ lines describe the edges. Each line contains three integers: the numbers of vertices connected by the edge (vertices are numbered from $1$ to $n$) and the weight of the edge. \OutputFile Print the sum of distances between all pairs of vertices in the tree. \includegraphics{https://static.e-olymp.com/content/db/dba4f48cb1423e95691f959cc49883945c08dedc.gif}
Time limit 1 second
Memory limit 128 MiB
Input example #1
3
1 2 1
1 3 3
Output example #1
5
Input example #2
5
1 3 7
4 1 2
4 5 5
2 4 3
Output example #2
30
Author Michael Medvediev