标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5723
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2969 Accepted Submission(s): 725
#include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; const int maxn=100005; int n,m; struct node { int x,y,w; node(int xx,int yy,int ww):x(xx),y(yy),w(ww) {} }; vector<node> a; struct Node { int y,w; Node(int yy,int ww):y(yy),w(ww) {} }; vector<Node> b[maxn]; int f[maxn]; bool cmp(const node &i,const node &j) { return i.w<j.w; } int finds(int x) {return f[x] == x?x:f[x] = finds(f[x]);} long long Kruskal() { long long ans=0; for(int i=1; i<=n; i++) f[i]=i; sort(a.begin(),a.end(),cmp); for(int i=0; i<a.size(); i++) { int x=finds(a[i].x); int y=finds(a[i].y); if(x==y)continue; f[x]=y; ans+=a[i].w; b[a[i].x].push_back(Node(a[i].y,a[i].w)); b[a[i].y].push_back(Node(a[i].x,a[i].w)); } return ans; } int s[maxn]; double d[maxn]; void dfs(int root,int father) { s[root]=1; for(int i=0; i<b[root].size(); i++) { int son=b[root][i].y; int l=b[root][i].w; if(son==father) continue; dfs(son,root); s[root]+=s[son]; d[root]+=d[son]+((double)s[son]*(n-s[son]))*l; } } int main() { int t; scanf("%d",&t); while(t--) { scanf("%d%d",&n,&m); a.clear(); for(int i=0; i<m; i++) { int x,y,w; scanf("%d%d%d",&x,&y,&w); a.push_back(node(x,y,w)); } memset(s,0,sizeof(s)); memset(d,0,sizeof(d)); for(int i=1; i<=n; i++) b[i].clear(); long long ans=Kruskal(); dfs(1,0); long long g=(long long)n*(n-1)/2; printf("%I64d %.2lf\n",ans,d[1]/(double)g); } return 0; }
hdu 5723 Abandoned country(最小生成树,dfs)
标签:
原文地址:http://www.cnblogs.com/q-c-y/p/5695904.html