题目大意
一棵树,需找到一条链,要求次此链层次从上到下,并且链上的值相加等于S,链的顶端不一定是根节点,问有多少条这种链
输入
第一行,n和S,代表n个节点
第二行,n个数,第i个数代表第i个节点的值
第3~n + 1行,每行两个数,x,y,代表x是y的父亲
输出
一个数,为有多少条这种链
样例输入
3 3
1 2 3
1 2
1 3
样例输出
2
数据范围
对于30%数据,
N
⩽
100
N \leqslant 100
N⩽100;
对于60%数据,
N
⩽
1000
N \leqslant 1000
N⩽1000;
对于100%数据,
N
⩽
100000
N \leqslant 100000
N⩽100000,所有权值以及S都不超过1000。
思路
循环n个节点,在每一个节点向上找一遍,判断是否等于S
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int F[100250], A[100250];
int n, m, x, y, Ans;
int Read()
{
int x = 0,f = 1;char c = getchar();
while(c < '0' || c > '9')c = getchar();
if(c == '-')f = -1, c = getchar();
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return x * f;
}
void Find(int k)
{
int Sum = 0;
while(k)
{
Sum += A[k];
if(Sum == m){Ans++;return;}
else if(Sum > m)return;
k = F[k];
}
}
int main()
{
// freopen("tree.in","r",stdin);
// freopen("tree.out","w",stdout);
n = Read(), m = Read();
for(int i = 1; i <= n; i++)A[i] = Read();
for(int i = 1; i < n; i++)
{
x = Read(), y = Read();
F[y] = x;
}
for(int i = 1; i <= n; i++)Find(i);
printf("%d", Ans);
fclose(stdin);
fclose(stdout);
return 0;
}