您的位置:首页 > 其它

hdu 5723(最小生成树)

2016-07-22 20:28 423 查看
#include <bits/stdc++.h>

#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;

#define LL long long
#define pii pair<int,int>
#define MP make_pair
#define ls i << 1
#define rs ls | 1
#define md (ll + rr >> 1)
#define lson ll, md, ls
#define rson md + 1, rr, rs
#define Pi acos(-1.0)
#define mod 1000000007
#define eps 1e-12
#define inf 0x3f3f3f3f
#define N 200010
#define M 1000020

struct edge{
int u, v, w;
void input(){
scanf("%d%d%d", &u, &v, &w);
}
}ee[M];
int n, m, fa
, c[M], id[M];
int fst
, vv[M], nxt[M], cost[M], e;
int sz
;
LL ans;
void init(){
memset(fst, -1, sizeof fst); e = 0;
}
void add(int u, int v, int w){
vv[e] = v, nxt[e] = fst[u], cost[e] = w, fst[u] = e++;
}
void dfs(int u, int p){
sz[u] = 1;
for(int i = fst[u]; ~i; i = nxt[i]){
int v = vv[i];
if(v == p) continue;
dfs(v, u);
sz[u] += sz[v];
ans += 1LL * (n - sz[v]) * sz[v] * cost[i];
}
}
int find(int x){
if(fa[x] != x) fa[x] = find(fa[x]);
return fa[x];
}
int main(){
int cas;
scanf("%d", &cas);
while(cas--){
ans = 0;
scanf("%d%d", &n, &m);
memset(c, 0, sizeof c);
for(int i = 1; i <= m; ++i){
ee[i].input();
c[ee[i].w]++;
}
for(int i = 1; i < M; ++i) c[i] += c[i-1];
for(int i = 1; i <= m; ++i)
id[c[ee[i].w]--] = i;
for(int i = 0; i <= n; ++i) fa[i] = i;
init();
LL tot = 0;
for(int i = 1; i <= m; ++i){
int x = id[i], u = ee[x].u, v = ee[x].v, w = ee[x].w;
if(find(u) == find(v)) continue;
fa[find(u)] = find(v);
add(u, v, w);
add(v, u, w);
tot += w;
}
dfs(1, -1);
double ret = 1.0 * ans / n / (n -1) * 2;
printf("%lld %.2f\n", tot, ret);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: