HDU 5723 Abandoned country 最小生成树 + 期望计算

http://acm.hdu.edu.cn/showproblem.php?pid=5723

Abandoned country

Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Problem Description
An abandoned country has n(n100000) villages which are numbered from 1 to n . Since abandoned for a long time, the roads need to be re-built. There are m(m1000000) roads to be re-built, the length of each road is wi(wi1000000) . Guaranteed that any two wi are different. The roads made all the villages connected directly or indirectly before destroyed. Every road will cost the same value of its length to rebuild. The king wants to use the minimum cost to make all the villages connected with each other directly or indirectly. After the roads are re-built, the king asks a men as messenger. The king will select any two different points as starting point or the destination with the same probability. Now the king asks you to tell him the minimum cost and the minimum expectations length the messenger will walk.
Input
The first line contains an integer T(T10) which indicates the number of test cases.
For each test case, the first line contains two integers n,m indicate the number of villages and the number of roads to be re-built. Next m lines, each line have three number i,j,wi , the length of a road connecting the village i and the village j is wi .
Output
output the minimum cost and minimum Expectations with two decimal places. They separated by a space.
Sample Input
1
4 6
1 2 1
2 3 2
3 4 3
4 1 4
1 3 5
2 4 6
Sample Output
6 3.33
Author
HIT
Source
题意:给定一个图,每条边边权不同,求问最小生成树的大小,并求出任意两点,在最小生成树上路径长度的期望。
思路:由于每条边权都不同,那么最小生成树是唯一的。求任意两点,在最小生成树上路径长度的期望,可以考虑计算每条边对答案的贡献,经过这条边的次数*这条边的边权就是贡献,次数为这条边两边点的个数的乘积。用第一次dfs求出每个子树的大小,用第二次dfs求出每条边两边点的数目即可。最后将总和除以总的方案数n*(n-1)/2得到最终的答案。