在這個問題中,給定一個值S和一棵樹。在樹的每個節點有一個正整數,問有多少條路徑的節點總和達到S。路徑中節點的深度必須是升序的。假設節點1是根節點,根的深度是0,它的兒子節點的深度爲1。路徑不必一定從根節點開始。
Input
第一行是兩個整數N和S,其中N是樹的節點數。
第二行是N個正整數,第i個整數表示節點i的正整數。
接下來的N-1行每行是2個整數x和y,表示y是x的兒子。
Output
輸出路徑節點總和爲S的路徑數量。
Sample Input
3 3
1 2 3
1 2
1 3
Sample Output
2
HINT
對於100%數據,N≤100000,所有權值以及S都不超過1000。
分析
因爲求的路徑都是從在包含根的一條路徑上。用dfs。記錄元素前綴和就好了。
代碼:
#define N 100005
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <queue>
#include <cmath>
using namespace std;
struct KK
{
int to,next;
}e[N*2];
int head[N];
int st[N],Q[N],sum[N];
int top,ans;
int s,n;
int cnt=0;
void add(int x,int y)
{
e[++cnt].to=y;e[cnt].next=head[x];head[x]=cnt;
}
void dfs(int dep,int now,int root)
{
st[++top]=now;
int need=lower_bound(st+1,st+top+1,now-s)-st;
if(st[need]+s==now && need>0 && need<=top)
ans++;
for(int i=head[dep];i;i=e[i].next)
{
if(e[i].to==root)
continue;
dfs(e[i].to,now+sum[e[i].to],dep);
}
top--;
}
int main()
{
scanf("%d%d",&n,&s);
for(int i=1;i<=n;i++)
scanf("%d",&sum[i]);
for(int i=1;i<n;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
}
st[++top]=0;
dfs(1,sum[1],0);
printf("%d\n",ans);
}