Problem Description
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
题意
n个城市m条路,国王想花最少的钱使得任意两个城市连通,最后问你国王任意两个点的距离期望
题解
第一问直接跑个最小生成树
第二问树上任意两点期望,可以发现两两点总数是n*(n-1)/2种情况,然后只需要dp出任意两点距离和,再用距离和/情况数
当n=1的时候直接输出0.00,然后n*(n-1)可能会爆所以得*1LL
代码
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 #define ll long long 5 6 const int maxn=1e5+5; 7 const int maxm=1e6+5; 8 9 int n,m; 10 int f[maxn]; 11 vector< pair<int,ll> >G[maxn]; 12 ll dp[maxn],sum[maxn],ans; 13 struct edge 14 { 15 int u,v; 16 ll w; 17 bool operator<(const edge& D)const{ 18 return w<D.w; 19 } 20 }edges[maxm]; 21 void dfs(int cur,int fa) 22 { 23 sum[cur]=1; 24 for(int i=0;i<G[cur].size();i++) 25 { 26 int son=G[cur][i].first; 27 ll w=G[cur][i].second; 28 if(fa==son)continue; 29 dfs(son,cur); 30 sum[cur]+=sum[son]; 31 dp[cur]+=dp[son]+sum[son]*(n-sum[son])*w; 32 } 33 } 34 int find(int x) 35 { 36 return f[x]==x?x:f[x]=find(f[x]); 37 } 38 void kruskal() 39 { 40 for(int i=1;i<=n;i++)f[i]=i; 41 sort(edges,edges+m); 42 int cnt=0; 43 for(int i=0;i<m;i++) 44 { 45 int u=edges[i].u; 46 int v=edges[i].v; 47 ll w=edges[i].w; 48 int fu=find(u); 49 int fv=find(v); 50 if(fu!=fv) 51 { 52 f[fu]=fv; 53 G[u].push_back({v,w}); 54 G[v].push_back({u,w}); 55 ans+=w; 56 if(++cnt==n-1)return; 57 } 58 } 59 } 60 int main() 61 { 62 int t,u,v; 63 ll w; 64 scanf("%d",&t); 65 while(t--) 66 { 67 ans=0; 68 scanf("%d%d",&n,&m); 69 for(int i=0;i<m;i++) 70 { 71 scanf("%d%d%lld",&u,&v,&w); 72 edges[i]={u,v,w}; 73 } 74 kruskal(); 75 dfs(1,1); 76 if(n==1)printf("%lld 0.00\n",ans); 77 else printf("%lld %.2f\n",ans,dp[1]*1.0/(1LL*n*(n-1)/2)); 78 for(int i=1;i<=n;i++) 79 { 80 dp[i]=sum[i]=0; 81 G[i].clear(); 82 } 83 } 84 return 0; 85 }