Untitled

mail@pastecode.io avatar
unknown
plain_text
5 months ago
1.8 kB
2
Indexable
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
vector<int>frq(N,0);
vector<int>a(N,0);
vector<vector<int>>adj(N);
vector<int>tin(N,0);
vector<int>sz(N,0);
long long ans=0;
int timer=1;
const long long mod=1e9+7;
int target;
vector<int>discover(N,0);
vector<int>bigchild(N);
void dfs(int node,int p)
{
    discover[timer]=node;
    tin[node]=timer++;
    sz[node]=1;
    int mx=-1,child=-1;
    for (auto t:adj[node])
    {
        if (t==p)continue;
        dfs(t,node);
        if (sz[t]>mx)
        {
            child=t;
            mx=sz[t];
        }
        sz[node]+=sz[t];
    }
    bigchild[node]=child;
}
void smalltobig(int node,int p,int keep=1)
{
    for (auto t:adj[node])
    {
        if (t==p || t==bigchild[node])continue;
        smalltobig(t,node,0);
    }
    if (bigchild[node]!=-1)
    {
        smalltobig(bigchild[node],node);
    }
    frq[0]=1;
    for (int i=5000;i>=a[node];i--)
        {
            frq[i]+=frq[i-a[node]];
            frq[i]%=mod;
        }

    for(auto t:adj[node])
    {
        if (t==p || t==bigchild[node])
            continue;
        for (int i=tin[t];i<=tin[t]+sz[t]-1;++i)
        {
            int nd=discover[i];
            for (int r=5000;r>=a[nd];r--){
                frq[r]+=frq[r-a[nd]];
                frq[r]%=mod;
            }
        }
    }
    ans+=frq[target];
    ans%=mod;
    if (!keep)
    {
        for (int i=0;i<=5000;++i)
            frq[i]=0;
        frq[0]=1;
    }
}
void solve()
{
    int n;
    cin>>n>>target;
    for (int i=1;i<=n;++i)
    {
        cin>>a[i];
    }
    for (int i=0;i<n-1;++i)
    {
        int u,v;
        cin>>u>>v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    dfs(1,1);
    smalltobig(1,1);
    cout<<ans;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    solve();
}
Leave a Comment