C. Alyona and the Tree
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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.
Example
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
Output
5
链接 http://codeforces.com/contest/682/problem/C
题意
给一棵树,每个节点和每条边都对应一个数值。两个节点间的距离为边上的权值之和。对于某个点来说,如果他到他的某个子节点的距离大于子节点上的数值,那么他是sad的。问最少去掉多少个节点,能使所有节点都不sad。
思路
dfs,贪心处理使当前路径之和最大,如果到达某节点时路径和大于点上的数值,那么这个点和这个点所有的子节点都需要去掉。dfs函数return当前节点及其子节点还未删去的数目。
代码
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
struct point
{
vector<int> son;
long long n,d;
}p[100010];
int ans;
int dfs (int k,long long sum)
{
int l=p[k].son.size(),n=0;
for (int i=0;i<l;i++)
{
n+=dfs(p[k].son[i],max(sum+p[k].d,(long long) 0));
}
if (sum+p[k].d>p[k].n)
{
ans+=1+n;
return 0;
}
else
{
return n+1;
}
}
int main()
{
int n,t;
long long c;
scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%I64d",&p[i].n);
for (int i=2;i<=n;i++)
{
scanf("%d %I64d",&t,&c);
p[t].son.push_back(i);
p[i].d=c;
}
dfs(1,0);
printf("%d",ans);
}
PS
现场理解错题意了。。以为是去掉边。。好蠢。。