2783: [JLOI2012]树 set

用set维护前缀和,每次在set中查找当前的前缀和 sumS ,如果存在则 ans+1

#include<iostream>
#include<cstdio>
#include<queue>
#include<set>
#include<algorithm>
#define ll long long 
using namespace std;
int n,S,cnt,ans;
int v[100005],head[100005],next[100005],list[100005];
multiset<int> s;
inline int read()
{
    int a=0,f=1; char c=getchar();
    while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
    while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
    return a*f;
}
inline void insert(int x,int y)
{
    next[++cnt]=head[x];
    head[x]=cnt;
    list[cnt]=y;
}
void dfs(int x,int sum)
{
    if (s.find(sum-S)!=s.end()) ans++;
    s.insert(sum);
    for (int i=head[x];i;i=next[i]) dfs(list[i],sum+v[list[i]]);
    s.erase(s.find(sum));
}
int main()
{
    n=read(); S=read();
    s.insert(0);
    for (int i=1;i<=n;i++) v[i]=read();
    for (int i=1;i<n;i++)
    {
        int u=read(),v=read();
        insert(u,v);
    }
    dfs(1,v[1]);
    cout << ans << endl;
    return 0;
}

你可能感兴趣的:(2783: [JLOI2012]树 set)