51nod 1679 连通率

前言

发现我现在树的题什么也不会了。。
就只会树剖和dsu。。

题解

暴力的做法很容易想到
就是枚举两个点,那么他对答案的贡献就是 2n(dep[x]+dep[y]2dep[LCA]+1) 2 n − ( d e p [ x ] + d e p [ y ] − 2 ∗ d e p [ L C A ] + 1 )
然后我们胡乱考虑一下,就可以吧答案拆成 2n/2(dep[x]+dep[y]2dep[LCA]+1) 2 n / 2 ( d e p [ x ] + d e p [ y ] − 2 ∗ d e p [ L C A ] + 1 )
然后后面这个式子,也是一样可以拆开的
也就是 2dep[x]2dep[y]/22dep[LCA]1 2 d e p [ x ] ∗ 2 d e p [ y ] / 2 2 ∗ d e p [ L C A ] − 1
于是我们就可以合并子树了
每一个子树里面记录一个 2dep[x] 2 d e p [ x ] 的和,这个显然可以用dsu优化
然后启发式合并把别的子树合并进去就可以了
时间复杂度是 O(nlogn) O ( n l o g n )
做完以后瞄了一眼题解,并不知道题解在讲什么。。

CODE:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const LL MOD=1e9+7;
const LL INV=500000004;
const LL N=100005;
LL pow[N],inv[N];
struct qq
{
    LL x,y,last;
}e[N*2];LL num,last[N];
LL n;
void init (LL x,LL y)
{
    num++;
    e[num].x=x;e[num].y=y;
    e[num].last=last[x];
    last[x]=num;
}
LL ans=0;
LL tot[N],son[N];
LL dep[N];
void dfs1 (LL x,LL fa)
{
    tot[x]=1;
    for (LL u=last[x];u!=-1;u=e[u].last)
    {
        LL y=e[u].y;
        if (y==fa) continue;
        dep[y]=dep[x]+1;dfs1(y,x);
        tot[x]=tot[x]+tot[y];
        if (tot[y]>tot[son[x]]) son[x]=y;
    }
}
LL lalal;
LL p;
LL o;
void solve (LL x,LL fa)
{
    ans=(ans+o*lalal%MOD*inv[dep[x]]%MOD*pow[p]%MOD*pow[p-1]%MOD)%MOD;
    for (LL u=last[x];u!=-1;u=e[u].last)
    {
        LL y=e[u].y;
        if (y==fa) continue;
        solve(y,x);
    }
}
void add (LL x,LL fa)
{
    lalal=(lalal+inv[dep[x]])%MOD;
    for (LL u=last[x];u!=-1;u=e[u].last)
    {
        LL y=e[u].y;
        if (y==fa) continue;
        add(y,x);
    }
}
void dfs (LL x,LL fa)
{
    for (LL u=last[x];u!=-1;u=e[u].last)
    {
        LL y=e[u].y;
        if (y==fa||y==son[x]) continue;
        lalal=0;dfs(y,x);
    }
    if (son[x]!=0)  {lalal=0;dfs(son[x],x);}
    p=dep[x];
    for (LL u=last[x];u!=-1;u=e[u].last)
    {
        LL y=e[u].y;
        if (y==fa||y==son[x]) continue;
        solve(y,x);
        add(y,x);
    }
    ans=(ans+o*lalal%MOD*pow[p-1]%MOD)%MOD; 
    lalal=(lalal+inv[dep[x]])%MOD;
}
int main()
{
    num=0;memset(last,-1,sizeof(last));
    scanf("%lld",&n);
    pow[0]=1;for (LL u=1;u<=n;u++) pow[u]=pow[u-1]*2%MOD;
    o=pow[n];
    inv[0]=1;for (LL u=1;u<=n;u++) inv[u]=inv[u-1]*INV%MOD;
    for (LL u=1;u<n;u++)
    {
        LL x,y;
        scanf("%lld%lld",&x,&y);
        init(x,y);init(y,x);
    }
    dep[1]=1;dfs1(1,0);
    dfs(1,0);
    printf("%lld\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值