首先最小生成树,然后dfs统计每条边经过了几棵子树 每条边经过的子树个数等于这条边连接的子树节点数*(n-子树节点数)因为这是一棵树每条边都能把树分成两个集合,假设第一个集合的元素数目为n1,第二个集合的元素数目为n2,那么从两个集合分别选出一点就有n1*n2种方案
#include<vector>
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<utility>
#define LL long long
#define maxn 100005
using namespace std;
LL n,m,fa[maxn];
double ex;
vector<LL>am[maxn];
vector<pair<LL,LL> >root[maxn];
bool sym[maxn];
struct node
{
LL x,y,dis;
}ed[maxn*10];
bool cmp(node no1,node no2)
{
return no1.dis<no2.dis;
}
LL getFarther(LL i)
{
if(i==fa[i])return i;
fa[i] = getFarther(fa[i]);
return fa[i];
}
LL krustral()
{
LL ans = 0;
sort(ed,ed+m,cmp);
for(int i=0;i<m;i++)
{
LL fx = getFarther(ed[i].x),fy = getFarther(ed[i].y);
if(fx!=fy)
{
fa[fy] = fx;
ans+=ed[i].dis;
root[ed[i].x].push_back(make_pair(ed[i].y,ed[i].dis));
root[ed[i].y].push_back(make_pair(ed[i].x,ed[i].dis));
}
}
return ans;
}
LL dfs(int pre)
{
sym[pre] = 1;
LL sum = 0;
for(int i=0;i<root[pre].size();i++)
{
if(!sym[root[pre][i].first])
{
LL pre1 = dfs(root[pre][i].first)+1;
ex =ex + root[pre][i].second*pre1*(n-pre1);
sum+=pre1;
}
}
sym[pre] = 0;
return sum;
}
double solve()
{
printf("%I64d ",krustral());
ex = 0.0;
LL pre = dfs(1);
return ex;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%I64d %I64d",&n,&m);
for(int i=1;i<=n;i++){root[i].clear();fa[i] = i;}
for(int i=0;i<m;i++) scanf("%d%d%d",&ed[i].x,&ed[i].y,&ed[i].dis);
printf("%.2f\n",solve()*2/(n*(n-1)));
}
return 0;
}