题意
传送门 P3066 [USACO12DEC]Running Away From the Barn
题解
考虑从根 D F S DFS DFS 将树表示为序列进行维护。设节点 i i i 到根节点的距离为 d [ i ] d[i] d[i],对于每个节点 u u u 只考虑以其为根的子树上的节点,对于满足条件的点对 ( u , v ) (u,v) (u,v),其 L C A LCA LCA 为 u u u,那么 d [ v ] = d [ u ] + d i s t ( u , v ) d[v]=d[u]+dist(u,v) d[v]=d[u]+dist(u,v)。对于一颗子树,其节点的 D F S DFS DFS 序是连续的,则问题转化为求以各节点 u u u 为根的子树上满足 d [ v ] ≤ d [ u ] + t d[v]\leq d[u]+t d[v]≤d[u]+t 的节点数量;用主席树维护即可。
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
#define maxn 200005
#define tree_size 4000005
typedef long long ll;
struct edge
{
int to;
ll cost;
};
int N, cnt, L[maxn], R[maxn], rt[maxn], cl[tree_size], cr[tree_size], sum[tree_size];
ll T, D[maxn], D2[maxn];
vector<edge> G[maxn];
void dfs(int v, ll d, int &k)
{
++k, L[v] = k, D[k] = d;
for (int i = 0; i < (int)G[v].size(); ++i)
{
edge &e = G[v][i];
dfs(e.to, e.cost + d, k);
}
R[v] = k;
}
int update(int pre, int x, int l, int r)
{
int cur = ++cnt;
cl[cur] = cl[pre], cr[cur] = cr[pre], sum[cur] = sum[pre] + 1;
if (r - l > 1)
{
int m = (l + r) >> 1;
x < m ? cl[cur] = update(cl[pre], x, l, m) : cr[cur] = update(cr[pre], x, m, r);
}
return cur;
}
int query(int u, int v, int x, int l, int r)
{
if (r - 1 <= x)
return sum[v] - sum[u];
if (x < l)
return 0;
int m = (l + r) >> 1;
return x < m ? query(cl[u], cl[v], x, l, m) : query(cr[u], cr[v], x, m, r) + sum[cl[v]] - sum[cl[u]];
}
int main()
{
scanf("%d%lld", &N, &T);
for (int i = 1; i < N; ++i)
{
int p;
ll w;
scanf("%d%lld", &p, &w);
G[p - 1].push_back(edge{i, w});
}
int k = -1;
dfs(0, 0, k);
memcpy(D2, D, sizeof(ll) * N);
sort(D, D + N);
int n = unique(D, D + N) - D;
for (int i = 0; i < N; ++i)
{
int x = lower_bound(D, D + n, D2[i]) - D;
rt[i + 1] = update(rt[i], x, 0, n);
}
for (int i = 0; i < N; ++i)
{
int x = upper_bound(D, D + n, D2[L[i]] + T) - D - 1;
printf("%d\n", query(rt[L[i]], rt[R[i] + 1], x, 0, n));
}
return 0;
}