Codeforces 682C. Alyona and the Tree

来源:互联网 发布:数控冲床编程教学 编辑:程序博客网 时间:2024/06/06 04:48
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 vertex1, 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 vertexu in subtree of vertexv such that dist(v, u) > au, whereau is the number written on vertexu, dist(v, u) is the sum of the numbers written on the edges on the path fromv tou.

Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is aleaf 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 integersa1, a2, ..., an (1 ≤ ai ≤ 109) is given, whereai is the number written on vertexi.

The next n - 1 lines describe tree edges:ith of them consists of two integerspi andci(1 ≤ pi ≤ n, - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 andpi with numberci 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
988 22 83 14 95 91 98 53 113 247 -81 671 649 655 126 -803 8
Output
5
这道题大意就是给你一棵树,从根节点开始如果一棵树的子树存在其祖先的边权值小于该点的权值那么就要去除改点,问最少去多少个这样的点才能保证这棵树是合法的.
做法很简单就是dfs直到遇到不合法的点,之后其子树就不用去搜素了.因为边的权值可能小于0,所以要满足sum=max(sum+edge[next],edge[next])(edge[next]为下一条边的权值);
注意一点,题目虽然说1<=n<=10^5 但是存的话最好开大点,不然会莫名TLE...
#define ll __int64#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int head[1000005];int mapp[1000005];int vis[1000005];int fre;struct p{    int  next,node,cost;}E[1000005];void insertt(int x,int y,int cst){    E[fre].node=y;    E[fre].next=head[x];    E[fre].cost=cst;    head[x]=fre++;}void dfs(int root,ll sum){    if (mapp[root]<sum) return;    vis[root]=1;    for (int  i=head[root];i!=-1;i=E[i].next)    {        if (!vis[E[i].node])        {            dfs(E[i].node,max(E[i].cost+sum,(ll)E[i].cost));        }    }}int main(){   int  n; fre=0;   scanf("%d",&n);   memset(vis,0,sizeof(vis));   memset(head,-1,sizeof(head));   for (int i=1;i<=n;i++)   {       scanf("%d",&mapp[i]);   }   for (int  i=1;i<n;i++)   {       int  a,b;       scanf("%d%d",&a,&b);       insertt(a,i+1,b);       insertt(i+1,a,b);   }   dfs(1,0);   int num=0;   for (int  i=1;i<=n;i++)   {       if (vis[i]) num++;   }   printf("%d\n",n-num);   return 0;}

























0 0
原创粉丝点击