bzoj 2783树

来源:互联网 发布:kmp算法next数组怎么求 编辑:程序博客网 时间:2024/05/16 14:01

在这个问题中,给定一个值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);}
1 0
原创粉丝点击