BZOJ4543 POI2014 Hotel加强版 【长链剖分】【DP】*

本文详细解析了 BZOJ4543 POI2014 Hotel 加强版问题,并提供了一种高效的数据结构实现方法。通过递归分解和动态规划技巧,解决了大规模数据输入下的复杂路径计算问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

BZOJ4543 POI2014 Hotel加强版


Description

同OJ3522
数据范围:n<=100000

Sample Input

7
1 2
5 7
2 5
2 3
5 6
4 5

Sample Output

5


 


#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define N 100010
LL pool[N<<4];
LL* top=pool;
LL* get(int len){LL* t=top;top+=len;return t;}
LL *f[N],*g[N];
int n;
LL ans=0;
vector<int> p[N];
int dep[N],lson[N];
void dfs1(int u,int fa){
    dep[u]=0;lson[u]=0;
    for(int i=0;i<p[u].size();i++){
        int v=p[u][i];
        if(v==fa)continue;
        dfs1(v,u);
        dep[u]=max(dep[u],dep[v]+1);
        if(dep[v]>dep[lson[u]])lson[u]=v;
    }
}
void dfs2(int u,int fa,int& maxlen,int blank){
    maxlen=max(maxlen,dep[u]);
    if(lson[u]){
        dfs2(lson[u],u,maxlen,blank+1);
        ans+=g[lson[u]][1];
        f[u]=f[lson[u]]-1;
        f[u][0]=1;
        g[u]=g[lson[u]]+1;
    }else{
        f[u]=get(maxlen+5+blank)+blank;
        g[u]=get(maxlen+5+blank);
        f[u][0]=1;
    }
    for(int i=0;i<p[u].size();i++){
        int v=p[u][i],mxlen=0;
        if(v==fa||v==lson[u])continue;
        dfs2(v,u,mxlen,0);
        for(int j=0;j<dep[v];j++)ans+=f[u][j]*g[v][j+1];
        for(int j=1;j<=dep[v]+1;j++)ans+=g[u][j]*f[v][j-1];
        for(int j=1;j<=dep[v]+1;j++)g[u][j]+=f[u][j]*f[v][j-1];
        for(int j=0;j<=dep[v];j++)f[u][j+1]+=f[v][j];
        for(int j=1;j<=dep[v];j++)g[u][j-1]+=g[v][j];
    }
}
int main(){
    scanf("%d",&n);
    for(int i=1;i<n;i++){
        int u,v;
        scanf("%d%d",&u,&v);
        p[u].push_back(v);
        p[v].push_back(u);
    }
    int mxlen=0;
    dfs1(1,0);
    dfs2(1,0,mxlen,0);
    printf("%lld",ans);
    return 0;
}

转载于:https://www.cnblogs.com/dream-maker-yk/p/9676294.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值