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:
大体题意:
有一颗树,告诉你n 个结点的值a[i],并且告诉你与之相连的路的权值w,问最少删除几个树叶使得这棵树上的没有不开心的树叶,所谓不开心的树叶,如果u是不开心结点,那么存在v使得两个结点路上的权值大于u 的值a[u]。
思路:
整体思路是算出合适的结点,用总结点减去合适的结点。
建立树用vector<pari<int,int > >g[maxn]数组来建立,g[i]表示i结点所连的所有结点,first 代表结点编号,second 代表两个结点之间路上的权值。然后从1号结点开始dfs,初始权值d为0,如果d和结点权值不符合要求的话 即d > a[i],直接retunrn ,否则++ans 代表这个点合适。然后再dfs 与这个合适结点相连的所有结点。
注意:因为题目中权值是有负数,所以在计算d时,如果d < 0 那么应该把d更正为0,也就是把这个方法舍去,而是选择最近的父节点!
最后输出n - ans即可!
在一点就是longlong 存d会爆int的!
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 100000 + 10;
vector<pair<int,int> >g[maxn];
int a[maxn],n,ans;
void dfs(int k,ll d){
if (d > a[k])return ;
++ans;
int len = g[k].size();
for (int i = 0; i < len; ++i){
dfs(g[k][i].first,max(g[k][i].second + d, 0ll));
}
}
int main(){
while(scanf("%d",&n) == 1){
ans = 0;
for (int i = 0; i <= n; ++i)g[i].clear();
for (int i = 1; i <= n; ++i){
scanf("%d",&a[i]);
}
for (int i = 2; i <= n; ++i){
int a,b;
scanf("%d%d",&a,&b);
g[a].push_back(make_pair(i,b));
}
dfs(1,0);
printf("%d\n",n-ans);
}
return 0;
}