Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).
Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.
The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.
Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such thatv controls u.
The first line contains single integer n (1 ≤ n ≤ 2·105).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers written in the vertices.
The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 ≤ pi ≤ n, 1 ≤ wi ≤ 109) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1).
It is guaranteed that the given graph is a tree.
Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.
5 2 5 1 4 6 1 7 1 1 3 5 3 6
1 0 1 0 0
5 9 7 8 6 5 1 1 2 1 3 1 4 1
4 3 2 1 0
In the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1controls the vertex 5).
题意:
给定一颗树,树上每条边每个点都有给定的权值。 如果 一个节点x 和 x的子孙y 满足 dis(x,y) <= A(y),则称x控制着y,现在要求每个点的控制的点的数目
思路:
做这道题真是被自己蠢到了。。。比赛时没有想出来。。。后来还想了好久。。。蒻蒻(。・・)ノ(。・・)ノ
当deep[x]-deep[p]<=A[x]时,可知p控制着x。那么维护一条到根的路径,每次添加一个新的路径前二分找到不能被控制的边界点,如果有的话将它的ans减一,递归处理儿子后,加上儿子的ans,如果有点刚好只能被儿子控制,则在之前的步骤减去。
代码:
#include<bits/stdc++.h>
using namespace std;
#define se second
#define fi first
struct edge{
int t;
int w;
edge(){};
edge(int _t,int _w){
t = _t ;
w = _w ;
}
};
int n;
int ans[200005];
long long A[200005];
long long deep[200005];
vector<pair<long long,int> > path;
vector<edge>G[200005];
void dfs(int x,int fa){
ans[x]=1;
int p = lower_bound(path.begin(),path.end(),make_pair(deep[x]-A[x],0))-path.begin()-1;
if(p>=0)ans[path[p].se]--;
path.emplace_back(make_pair(deep[x],x));
for(auto& it:G[x]){
if(it.t!=fa){
deep[it.t]=deep[x]+it.w;
dfs(it.t,x);
ans[x]+=ans[it.t];
}
}path.pop_back();
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%I64d",&A[i]);
}for(int i=2,f,w;i<=n;i++){
scanf("%d%d",&f,&w);
G[f].push_back(edge(i,w));
}dfs(1,1);
for(int i=1;i<=n;i++)
printf("%d ",ans[i]-1);
return 0;
}