原题
An abandoned country has n(n≤100000) villages which are numbered from 1 to n. Since abandoned for a long time, the roads need to be re-built. There are m(m≤1000000) roads to be re-built, the length of each road is wi(wi≤1000000). 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(T≤10) 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 possible length of the longest of all meetings, if meetings are arranged optimally according to the above rules.
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
解题思路
本体分为两问,第一问为求修路的最小花费,也就是求无向图的最小生成树,第二问为在这个生成树上,任意两点间距离的期望(因为速度是一定的,时间与路程成正比)。求最小生成树直接用Kruskal算法,然后在求期望时,可以用dfs的方法所有的总时间,除以所有的方法数。
利用pair数据结构可以简化dfs的函数,提高速度,减小代码的复杂性
注意
采用long long型,注意保留小数位数
AC代码
#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100002;
const int maxe=1000005;
struct Edge{
int f,t,w;
};
Edge edge[maxe];
vector<pair<int ,int> > a[maxn];
int n,m,t;
int vis[maxn];
int pre[maxn];
long long ans;
bool cmp(Edge a,Edge b){
return a.w<b.w;
}
int find(int x){
if(x!=pre[x]){
pre[x]=find(pre[x]);
}
return pre[x];
}
void merge(int x,int y){
int fx=find(x),fy=find(y);
if(fx!=fy)pre[fx]=fy;
}
long long dfs(int x){
vis[x]=1;
long long now=0;
long long all=1;
int an=a[x].size();
for(int i=0;i<an;i++){
int b=a[x][i].first;
if(!vis[b]){
now=dfs(b);
all+=now;
ans+=now*(n-now)*a[x][i].second;
}
}
return all;
}
int main(){
cin>>t;
while(t--){
memset(vis,0,sizeof vis);
cin>>n>>m;
ans=0;
for(int i=1;i<=n;i++){
pre[i]=i;
}
for(int i=1;i<=n;i++)
a[i].clear();
for(int i=1;i<=m;i++){
scanf("%d%d%d",&edge[i].f,&edge[i].t,&edge[i].w);
}
sort(edge+1,edge+m+1,cmp);
long long sum=0;
for(int i=0;i<=m;i++){
int fx=find(edge[i].f);
int fy=find(edge[i].t);
if(fx!=fy){
sum+=edge[i].w;
merge(fx,fy);
a[edge[i].f].push_back(make_pair(edge[i].t,edge[i].w));
a[edge[i].t].push_back(make_pair(edge[i].f,edge[i].w));
}
}
dfs(1);
double y=1.0*n*(n-1)/2;
printf("%lld %.2lf\n",sum,double(ans/y));
}
}