HDU 5723 Abandoned country(kruskal+dp树上任意两点距离和)

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

代码

 #include <bits/stdc++.h>
using namespace std; #define ll long long const int maxn=1e5+;
const int maxm=1e6+; int n,m;
int f[maxn];
vector< pair<int,ll> >G[maxn];
ll dp[maxn],sum[maxn],ans;
struct edge
{
int u,v;
ll w;
bool operator<(const edge& D)const{
return w<D.w;
}
}edges[maxm];
void dfs(int cur,int fa)
{
sum[cur]=;
for(int i=;i<G[cur].size();i++)
{
int son=G[cur][i].first;
ll w=G[cur][i].second;
if(fa==son)continue;
dfs(son,cur);
sum[cur]+=sum[son];
dp[cur]+=dp[son]+sum[son]*(n-sum[son])*w;
}
}
int find(int x)
{
return f[x]==x?x:f[x]=find(f[x]);
}
void kruskal()
{
for(int i=;i<=n;i++)f[i]=i;
sort(edges,edges+m);
int cnt=;
for(int i=;i<m;i++)
{
int u=edges[i].u;
int v=edges[i].v;
ll w=edges[i].w;
int fu=find(u);
int fv=find(v);
if(fu!=fv)
{
f[fu]=fv;
G[u].push_back({v,w});
G[v].push_back({u,w});
ans+=w;
if(++cnt==n-)return;
}
}
}
int main()
{
int t,u,v;
ll w;
scanf("%d",&t);
while(t--)
{
ans=;
scanf("%d%d",&n,&m);
for(int i=;i<m;i++)
{
scanf("%d%d%lld",&u,&v,&w);
edges[i]={u,v,w};
}
kruskal();
dfs(,);
if(n==)printf("%lld 0.00\n",ans);
else printf("%lld %.2f\n",ans,dp[]*1.0/(1LL*n*(n-)/));
for(int i=;i<=n;i++)
{
dp[i]=sum[i]=;
G[i].clear();
}
}
return ;
}
上一篇:Android开发 Unity3D基础 Android Development


下一篇:模板倍增LCA 求树上两点距离 hdu2586