[BZOJ3011] [Usaco2012 Dec]Running Away From the Barn

题目描述

Description

It's milking time at Farmer John's farm, but the cows have all run away! Farmer John needs to round them all up, and needs your help in the search. FJ's farm is a series of N (1 <= N <= 200,000) pastures numbered 1...N connected by N - 1 bidirectional paths. The barn is located at pasture 1, and it is possible to reach any pasture from the barn. FJ's cows were in their pastures this morning, but who knows where they ran to by now. FJ does know that the cows only run away from the barn, and they are too lazy to run a distance of more than L. For every pasture, FJ wants to know how many different pastures cows starting in that pasture could have ended up in. Note: 64-bit integers (int64 in Pascal, long long in C/C++ and long in Java) are needed to store the distance values.
给出以1号点为根的一棵有根树,问每个点的子树中与它距离小于l的点有多少个。

Input

Line 1: 2 integers, N and L (1 <= N <= 200,000, 1 <= L <= 10^18)

Lines 2..N: The ith line contains two integers p_i and l_i. p_i (1 <= p_i < i) is the first pasture on the shortest path between pasture i and the barn, and l_i (1 <= l_i <= 10^12) is the length of that path.

Output

Lines 1..N: One number per line, the number on line i is the number pastures that can be reached from pasture i by taking roads that lead strictly farther away from the barn (pasture 1) whose total length does not exceed L.

Sample Input

4 5 
1 4
2 3
1 5 

Sample Output

3 
2 
1
1

题目分析

orz可并堆 序+树状数组+双指针貌似能搞。

#include <cstdio>
#include <cstring>
#include <set>
#include <map>
#include <vector>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;
int n,tot,now;
struct your
{
    long long dis;
    int id;
}a[200100];
long long m;
int head[200100],to[400100],net[400100];
long long val[200100];
int f[200100],in[200100],out[200100];
void add(int x,int y,long long c)
{
    net[++tot]=head[x],head[x]=tot,to[tot]=y,val[tot]=c;
}
void dfs(int x)
{
    a[x].id=x,in[x]=++now;
    for(int i=head[x];i;i=net[i]) 
        a[to[i]].dis=a[x].dis+val[i],dfs(to[i]);
    out[x]=now;
}
void update(int x,int c)
{
    for(;x<=n;x+=x&-x) f[x]+=c; 
}
int ask(int x)
{
    int sum=0;
    for(;x;x-=x&-x) sum+=f[x];
    return sum;
}
int ans[200100];
int cmp(your j,your k) { return j.dis<k.dis; }
int main()
{
    scanf("%d%lld",&n,&m);
    for(int x,i=2;i<=n;i++)
    {
        long long c;
        scanf("%d%lld",&x,&c),add(x,i,c);
    }
    dfs(1);
    int j=n;
    sort(a+1,a+n+1,cmp);
    for(int i=n;i>=1;i--)
    {
        for(;a[j].dis-a[i].dis>m&&j;j--) update(in[a[j].id],-1);
        update(in[a[i].id],1);
        ans[a[i].id]=ask(out[a[i].id])-ask(in[a[i].id]-1);
    }
    for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
    return 0;
}

发表评论

邮箱地址不会被公开。 必填项已用*标注