1371. Cargo Agency

http://acm.timus.ru/problem.aspx?space=1&num=1371

树形DP  不过一遍DFS 就能可以

需要注意的 是 N=50000 时 需要用 long long  或者 unsigned int

还有超栈的话 需要 自己可一个较大的栈区

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<algorithm>

using namespace std;
#pragma comment(linker,"/STACK:1000000000,1000000000")

#define LL long long

const int INF=0x3f3f3f3f;
const int N=50005;
struct node
{
    int next;
    LL numnode;
    LL selft;
    LL ans;
}head[N];
int I;
struct tt
{
    int j,next,t;
}side[N*2];
void build(int i,int j,int t)
{
    side[I].j=j;
    side[I].t=t;
    side[I].next=head[i].next;
    head[i].next=I++;
}
void dfs(int x,int pre)
{
    head[x].selft=0;
    head[x].numnode=0;
    head[x].ans=0;
    for(int t=head[x].next;t!=-1;t=side[t].next)
    {
        int l=side[t].j;
        if(l!=pre)
        {
            dfs(l,x);
            LL w=head[l].numnode*(LL)(side[t].t)+head[l].selft;
            head[x].ans+=head[l].ans;
            head[x].ans+=(head[x].numnode*w);
            head[x].ans+=(head[x].selft*head[l].numnode);
            head[x].selft+=w;
            head[x].numnode+=head[l].numnode;
        }
    }
    ++head[x].numnode;
    head[x].ans+=head[x].selft;
}
int main()
{
    //freopen("data.txt","r",stdin);
    unsigned int n;
    while(cin>>n)
    {
        for(unsigned int i=1;i<=n;++i)
        head[i].next=-1;
        I=0;
        for(unsigned int i=1;i<n;++i)
        {
            int l,r,t;
            scanf("%d %d %d",&l,&r,&t);
            build(l,r,t);
            build(r,l,t);
        }
        dfs(1,-1);
        double temp=(n*(n-1)/2);
        printf("%.4lf\n",double(head[1].ans)/temp);
    }
    return 0;
}

 

 

转载于:https://www.cnblogs.com/liulangye/archive/2012/10/07/2714031.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值