题目链接:点这里!!!
题意:叫你先求个最小生成树,然后在树上随机选两个点,求这两个点的距离的期望。
题解:
先利用kruskal求个最小生成树,然后在树上跑dfs,我们计算树上的每条边对于答案的贡献就ok了!!!
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<vector>
#include<bitset>
#include<set>
#include<queue>
#include<stack>
#include<map>
#include<cstdlib>
#include<cmath>
#define LL long long
#define pb push_back
#define pa pair<int,int>
#define clr(a,b) memset(a,b,sizeof(a))
#define lson lr<<1,l,mid
#define rson lr<<1|1,mid+1,r
#define bug(x) printf("%d++++++++++++++++++++%d\n",x,x)
#define key_value ch[ch[root][1]][0]
#pragma comment(linker, "/STACK:102400000000,102400000000")
const LL MOD = 1000000007;
const int N = 1e5+15;
const int maxn = 1e5+15;
const int letter = 130;
const LL INF = 1e18;
const double pi=acos(-1.0);
const double eps=1e-10;
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m,father[N],head[N],tot,ps[N],vv[N];
struct node{
int x,y,v;
bool operator < (const node&p)const {
return v<p.v;
}
}p[N*10];
struct edges{
int to,next,val;
}e[N<<1];
void addedges(int u,int v,int val){
e[tot].to=v,e[tot].val=val,e[tot].next=head[u],head[u]=tot++;
}
int Find(int x){
if(x==father[x]) return x;
return father[x]=Find(father[x]);
}
void init(int n){
for(int i=1;i<=n;i++) father[i]=i;
clr(head,-1),tot=0,clr(ps,0),clr(vv,0);
}
void dfs(int x,int fa){
ps[x]=1;
for(int i=head[x];i!=-1;i=e[i].next){
int to=e[i].to;
if(fa==to) continue;
vv[to]=e[i].val;
dfs(to,x);
ps[x]+=ps[to];
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
init(n);
for(int i=0;i<m;i++){
scanf("%d%d%d",&p[i].x,&p[i].y,&p[i].v);
}
sort(p,p+m);
int vs=0;
LL sum=0;
for(int i=0;i<m;i++){
int xx=Find(p[i].x),yy=Find(p[i].y);
if(xx!=yy){
addedges(p[i].x,p[i].y,p[i].v);
addedges(p[i].y,p[i].x,p[i].v);
father[xx]=yy;
sum+=1LL*p[i].v;
vs++;
}
}
dfs(1,-1);
LL x=0,y=1ll*n*(n-1)/2ll;
for(int i=2;i<=n;i++) {
x+=1ll*vv[i]*ps[i]*(n-ps[i]);
}
/// if(n==1) {printf("0 0.00");continue;}
printf("%I64d %.2f\n",sum,1.0*x/y);
}
return 0;
}
/*
100
6 5
1 2 1
4 2 2
1 3 3
3 5 5
3 6 4
*/