Hdu-5723 最小生成树+树上求和期望

Hdu-5723

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 cost and minimum Expectations with two decimal places. They separated by a space.
 

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

1、用克鲁斯卡尔/普里姆求最小生成树
2、求树上求和期望

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> P;
#define gt getchar()
#define line '\n'
const int N=1e5+9;
const int M=1e6+9;
int read(){LL x=0,op=1;char c=gt;while(!isdigit(c)){if(c=='-')op=-1;c=gt;}while(isdigit(c))x=x*10+c-48,c=gt;return op*x;}
int H[N],k,n;
int dp[N],f[N];
double ans;
struct Edge{int u,v,w,pre;}E[M<<1],e[M];
bool cmp(Edge A,Edge B){return A.w<B.w;}
int get(int x){if(x!=f[x])f[x]=get(f[x]);return f[x];}
void add(int u,int v,int w){E[++k].pre=H[u];E[k].v=v;E[k].w=w;H[u]=k;}
void dfs(int u,int e)
{
	dp[u]=1;int i=H[u];while(i+1){
		int v=E[i].v,w=E[i].w;
		if((i^1)!=e){
			dfs(v,i);
			dp[u]+=dp[v];
			ans+=1LL*(n-dp[v])*dp[v]*w;
		}
		i=E[i].pre;
	}
}
int main()
{
	int m,u,v,w;
	int T=read(); while(T--){
		memset(H,-1,sizeof(H));
		ans=0,k=-1;LL val=0;
		n=read(),m=read(); for(int i=1;i<=m;++i)e[i].u=read(),e[i].v=read(),e[i].w=read();
		for(int i=1;i<=n;++i)f[i]=i;
		sort(e+1,e+m+1,cmp);
		for(int i=1;i<=m;++i){
			u=e[i].u,v=e[i].v,w=e[i].w;
			int x=get(u),y=get(v);
			if(x==y)continue;
			f[x]=y;
			add(u,v,w);
			add(v,u,w);
			val+=w;
		}
		dfs(1,-888);cout<<val<<" ";
		cout<<fixed<<setprecision(2)<<ans*2/n/(n-1)<<line;
	}
}

猜你喜欢

转载自www.cnblogs.com/ZeroOne-World/p/12548637.html