给定一个图求其最小生成树,并且算出最小生成树上任意两个点的期望距离
因为题目中说到每条边的边权都是唯一的,所以可以知道最小生成树唯一
然后求期望距离。点的数目非常大所以求出任意两点间距离在算期望距离是不现实的。
但是根据期望的累加性质可以想到,对于每条边,他对期望的贡献是经过他的路径数量*边权。
而经过这条边的数目为这条边左边的点和右边点的积。最后问题转化成统计一棵树上每个点他的子树的点数目
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <string.h>
#include <string>
#include <iomanip>
#include <cstring>
#include <vector>
#include <functional>
#include <cmath>
#include <sstream>
#include <set>
using namespace std;
#define PI acos(-1.0)
#define sp system("pause")
typedef long long ll;
typedef unsigned long long ull;
const ll mod = 1000000007;
#define PI acos(-1.0)
struct Edge
{
ll p,n, c;
Edge(){ p = n = c = 0; }
Edge(ll x, ll y, ll z) :p(x), n(y), c(z){}
friend bool operator<(const Edge& x, const Edge &y)
{
return x.c < y.c;
}
};
bool vis[100000 + 20];
int fa[100000 + 20];
int getfa(int x)
{
return fa[x] == x ? x : fa[x] = getfa(fa[x]);
}
ll cot[100000 + 20];
vector<Edge>g[100000 + 20];
vector<Edge>edge;
ll n, m;
double ans = 0;
void init()
{
memset(cot, 0, sizeof cot);
memset(vis, false, sizeof vis);
for (int i = 0; i <= 100000; i++)
{
g[i].clear();
}
edge.clear();
ans = 0;
}
void dfs(int x)
{
vis[x] = true;
for (int i = 0; i < g[x].size(); i++)
{
if (!vis[g[x][i].n])
{
dfs(g[x][i].n);
ans += (cot[g[x][i].n] * 1.0*(n - cot[g[x][i].n])*g[x][i].c / (n*(n - 1)*1.0 / 2.0));
cot[x] += cot[g[x][i].n];
}
}
cot[x]++;
}
int main()
{
int T;
cin >> T;
while (T--)
{
cin >> n >> m;
init();
ll ans1 = 0;
for (int i = 0; i <= n; i++)fa[i] = i;
for (int i = 0; i < m; i++)
{
Edge x;
scanf("%lld%lld%lld", &x.p, &x.n, &x.c);
edge.push_back(x);
}
sort(edge.begin(), edge.end());
ll cot = 0;
for (int i = 0; i < m; i++)
{
int x = getfa(edge[i].n), y = getfa(edge[i].p);
if (x != y)
{
cot++;
fa[x] = y;
ans1 += edge[i].c;
g[edge[i].n].push_back(Edge(edge[i].n, edge[i].p, edge[i].c));
g[edge[i].p].push_back(Edge(edge[i].p, edge[i].n, edge[i].c));
}
if (cot == n - 1)break;
}
dfs(1);
printf("%lld %.2f\n", ans1, ans);
}
}