Codeforces Round #358 (Div. 2) Alyona and the Tree
题目连接:
http://www.codeforces.com/contest/682/problem/C
Description
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?
Input
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.
Output
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.
Sample Input
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
Sample Output
5
题解
dfs遍历这棵树,判断u点是否需要删去,不需要就继续递归,并更新ans,需要则下面的子树都要删,所以就不用递归,直接return就行了
代码
/* *********************************************** Author :shallowdream Created Time :2016-06-18 02:07:55 File Name :E:/ACM/codeforce/Codeforces Round #358 (Div. 2) ************************************************ */ #include<bits/stdc++.h> using namespace std; const int MAXN = 100000+7; struct Edge{ int to,w,next; }; Edge edge[2*MAXN]; int tot,head[MAXN]; int ans,a[MAXN]; void init() { tot=0; ans=0; memset(head,-1,sizeof(head)); } void addedge(int u,int v,int w) { edge[tot].to=v; edge[tot].w=w; edge[tot].next=head[u]; head[u]=tot++; } void dfs(int u,int pre,long long w) { if(a[u]<w) return; ans++; for(int i=head[u];i!=-1;i=edge[i].next){ int v=edge[i].to; if(v==pre) continue; dfs(v,u,max(0LL,w+edge[i].w)); } } int main() { int N; int v,w; scanf("%d",&N); init(); for(int i=1;i<=N;i++) scanf("%d",&a[i]); for(int i=2;i<=N;i++){ scanf("%d%d",&v,&w); addedge(i,v,w); addedge(v,i,w); } dfs(1,1,0); printf("%d",N-ans); return 0; }