hdu5723 Abandoned country(最小生成树+期望)(2016多校第一场A题)

题目链接:点这里!!!


题意:叫你先求个最小生成树,然后在树上随机选两个点,求这两个点的距离的期望。


题解:

先利用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
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值