3011: [Usaco2012 Dec]Running Away From the Barn

题目链接

题目大意:给出以1号点为根的一棵有根树,问每个点的子树中与它距离小于等于(题面上漏了等于)l的点有多少个

题解:考虑自上而下推出答案,但是答案的转移无法直接dp实现
那么从下到上维护可并大根堆,堆中存储每个点到根的距离
堆顶大于l就弹出

我的收获:树上自下而上思想

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int M=200005;
#define ll long long

int n;
int t,head[M];
int root[M],size[M];
ll I,k[M];

struct edge{int to,nex;ll val;}e[M];

void add(int u,int v,ll w){e[t].to=v,e[t].val=w,e[t].nex=head[u],head[u]=t++;}

struct Skew_Heap{
    int c[M][2];
    int merge(int x,int y)
    {
        if(!x||!y) return x+y;
        if(k[x]<k[y]) swap(x,y);
        c[x][1]=merge(c[x][1],y);
        root[c[x][1]]=x;
        swap(c[x][0],c[x][1]);
        return x;
    }
    void pop(int &x){x=merge(c[x][0],c[x][1]);}
}q; 

void dfs(int x)
{
    size[x]=1;
    for(int v,i=head[x];i!=-1;i=e[i].nex)
        k[v=e[i].to]=k[x]+e[i].val,dfs(v),size[x]+=size[v],root[x]=q.merge(root[x],root[v]);
    while(k[root[x]]>I+k[x])
        size[x]--,q.pop(root[x]);
} 

void work()
{
    for(int i=1;i<=n;i++) root[i]=i;
    dfs(1);
    for(int i=1;i<=n;i++) printf("%d\n",size[i]);
}

void init()
{
    cin>>n>>I;
    int fa;ll z;memset(head,-1,sizeof(head));
    for(int i=2;i<=n;i++) scanf("%d%lld",&fa,&z),add(fa,i,z);
}

int main()
{
    init(),work();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值