这是一道省选题,好久没有做过这么好的题了。
第一次接触到“树上前缀和”这种神奇的东西,现在我有学会了一种新的做题思路。
原来树上的前缀和,并不是所有的链上的前缀和,而是当前DFS的链上的前缀和,而维护这个前缀和,就需要桶,或是STL里的容器之类的东西,在这里选的是set。
这个题之所以能用前缀和,是因为题目要求的路径是向下的,没有拐点,所以说才能用前缀和。
个人正在考虑,如何在链有拐点的情况下使用前缀和,
也欢迎各位dalao支招。
至于如何做,就不在赘述了。
上代码吧
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdio>
#include<cmath>
#include<set>
using namespace std;
multiset <int> st;
int a[100000+666];
struct edge{
int to;int next;
};
edge e[100000+666];
int h[100000+666];
int sum[100000+666];
int fa[100000+666];
int n;int s;
inline int ra()
{
int x=0;char ch=getchar();int flag=1;
while(ch>'9'||ch<'0'){if(ch=='-')flag=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x*=10;x+=ch-'0';ch=getchar();}
return x*flag;
}
int p;
int root;
int ans;
void add(int a,int b)
{
p++;
e[p].to=b;
e[p].next=h[a];
h[a]=p;
return;
}
void dfs(int now)
{
sum[now]=sum[fa[now]]+a[now];
st.insert(sum[now]);
if(st.count(sum[now]-s))ans++;
for(int i=h[now];i;i=e[i].next)
{
dfs(e[i].to);
}
st.erase(sum[now]);
return;
}
int main()
{
n=ra();s=ra();
for(int i=1;i<=n;i++)a[i]=ra();
for(int i=1;i<=n-1;i++)
{
int x,y;
x=ra();y=ra();
add(x,y);
fa[y]=x;
}
st.insert(0);
for(int i=1;i<=n;i++)
{
if(fa[i]==0)root=i;
}
dfs(root);
//dfs(1);
cout<<ans<<endl;
return 0;
}