bzoj 3011: [Usaco2012 Dec]Running Away From the Barn

题意:

给出以1号点为根的一棵有根树,问每个点的子树中与它距离小于等于l的点有多少个。

题解:

左偏数模板题。
维护下dep就可以了。
code:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#define LL long long
using namespace std;
struct node{
    int y,next;
    LL c;
}a[200010];int len=0,last[200010];
int n;
LL L;
struct trnode{
    int lc,rc,d;
    LL c;
    trnode() {lc=rc=d=0;}
}tr[200010];
int ans[200010],root[200010];
LL dep[200010];
void ins(int x,int y,LL c)
{
    a[++len].y=y;a[len].c=c;
    a[len].next=last[x];last[x]=len;
}
int merge(int x,int y)
{
    if(!x||!y) return x+y;
    if(tr[x].c<tr[y].c) swap(x,y);
    tr[x].rc=merge(tr[x].rc,y);
    if(tr[tr[x].rc].d>tr[tr[x].lc].d) swap(tr[x].lc,tr[x].rc);
    tr[x].d=tr[tr[x].rc].d+1;
    return x;
}
void dfs(int x,int fa,LL c)
{
    dep[x]=dep[fa]+c;root[x]=x;
    tr[x].c=dep[x];tr[x].d=1;ans[x]=1;
    for(int i=last[x];i;i=a[i].next)
    {
        int y=a[i].y;
        dfs(y,x,a[i].c);ans[x]+=ans[y];
        root[x]=merge(root[x],root[y]);
        while(tr[root[x]].c>dep[x]+L) ans[x]--,root[x]=merge(tr[root[x]].lc,tr[root[x]].rc);
    }
}
int main()
{
    scanf("%d %lld",&n,&L);
    for(int i=2;i<=n;i++)
    {
        int fa;LL c;scanf("%d %lld",&fa,&c);
        ins(fa,i,c);
    }
    dfs(1,0,0);
    for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值