思路:可以知道的是如果u这个结点删除,那么以u为根的子树也要删除,另外注意的是这个不开心值不一定要从根节点开始计算的,然后DFS一波就好了
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int maxn = 1e5+7;
int a[maxn];
vector<pair<int,int> >e[maxn];
int ans;
void dfs(int u,int fa,LL dis)
{
if(dis>a[u])
return;
ans++;
for(int i = 0;i<e[u].size();i++)
{
int v = e[u][i].first;
int w = e[u][i].second;
if(v==fa)
continue;
dfs(v,u,max(0LL,w+dis));
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 1;i<=n;i++)
scanf("%d",&a[i]);
for(int i = 1;i<=n-1;i++)
{
int p,c;
scanf("%d%d",&p,&c);
e[i+1].push_back(make_pair(p,c));
e[p].push_back(make_pair(i+1,c));
}
dfs(1,0,0);
printf("%d\n",n-ans);
}
Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.
The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.
Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.
Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?
In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree.
In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i.
The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.
Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.
9 88 22 83 14 95 91 98 53 11 3 24 7 -8 1 67 1 64 9 65 5 12 6 -80 3 8
5
The following image represents possible process of removing leaves from the tree:
![](https://i-blog.csdnimg.cn/blog_migrate/02fa27e54826f0191db512f3bf69f177.png)