Codeforces #101D: Castle 题解

尝试思考每棵子树应该按照什么样的顺序访问
要访问完一棵树的总时间肯定是这棵树内所有的边权之和×2,将这个值定义为 T(x) T ( x ) ,其中 x x 表示子树的根,再定义sz(x)表示以 x x 为根的子树的节点数,考虑某个节点的两棵子树x,y,如果先访问 x x 比先访问y更优,那么应该满足如下条件:

T(x)+T(x)sz(y)+T(y)<T(y)T(y)sz(x)+T(x) T ( x ) + T ( x ) ∗ s z ( y ) + T ( y ) < T ( y ) ∗ T ( y ) ∗ s z ( x ) + T ( x )

大概可以这样理解:如果先走 x x ,那么y中所有的节点都要多等一个 T(x) T ( x ) 的时间,反之亦然
两边约一下,得到 T(x)sz(y)<T(y)sz(x) T ( x ) ∗ s z ( y ) < T ( y ) ∗ s z ( x ) ,按照这个规则确定子树的访问顺序,再搜一遍就好

*注意一下虽然 T(x) T ( x ) 是不爆long long的,但cmp函数中 T(x)sz(y) T ( x ) ∗ s z ( y ) 会爆long long,要小心

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <utility>
#include <cctype>
#include <algorithm>
#include <bitset>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <cmath>
#define LL long long
#define LB long double
#define x first
#define y second
#define Pair pair<int,int>
#define pb push_back
#define pf push_front
#define mp make_pair
#define LOWBIT(x) x & (-x)
using namespace std;

const int MOD=100003;
const LL LINF=2e16;
const int INF=1e9;
const int magic=348;
const double eps=1e-10;
const double pi=acos(-1);

inline int getint()
{
    char ch;int res;bool f;
    while (!isdigit(ch=getchar()) && ch!='-') {}
    if (ch=='-') f=false,res=0; else f=true,res=ch-'0';
    while (isdigit(ch=getchar())) res=res*10+ch-'0';
    return f?res:-res;
}

int n;
vector<Pair> v[100048];
int sz[100048],edgelen[100048];

inline void dfs(int cur,int father)
{
    int i,y;sz[cur]=1;edgelen[cur]=0;
    for (i=0;i<int(v[cur].size());i++)
    {
        y=v[cur][i].x;
        if (y!=father)
        {
            dfs(y,cur);
            sz[cur]+=sz[y];
            edgelen[y]+=v[cur][i].y*2;edgelen[cur]+=edgelen[y];
        }
    }
}

inline bool cmp(Pair x,Pair y) {return (long long)edgelen[x.x]*sz[y.x]<(long long)edgelen[y.x]*sz[x.x];}

LL ans=0;
inline void Dfs(int cur,int father,int tm)
{
    int i,y;sort(v[cur].begin(),v[cur].end(),cmp);
    ans+=tm;int curtm=tm;
    for (i=0;i<int(v[cur].size());i++)
    {
        y=v[cur][i].x;
        if (y!=father) Dfs(y,cur,curtm+v[cur][i].y),curtm+=edgelen[y];
    }
}

int main ()
{
    int i,x,y,c;n=getint();
    for (i=1;i<=n-1;i++)
    {
        x=getint();y=getint();c=getint();
        v[x].pb(mp(y,c));v[y].pb(mp(x,c));
    }
    dfs(1,-1);
    Dfs(1,-1,0);
    double fans=ans;fans/=(n-1);
    printf("%.6lf\n",fans);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值