对于一个点,要么选要么不选,选了的话就递归,不选的话他的子树的点都不选。
有可能因为选择相等的点而重复,所以我们每次都dfs权值相等的点时,只考虑编号更大的点。
代码:
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
long long d,dp[2005],V[2005],n,u,v,ans;
vector<int>G[2005];
void dfs(int s,int fa,int rt)
{
dp[s]=1;
for(int i=0,to;i<G[s].size();i++)
{
to=G[s][i];
if(to==fa) continue;
dfs(to,s,rt);
if((V[rt]>V[to]&&V[rt]-V[to]<=d)||(V[rt]==V[to]&&rt<to)) dp[s]=(dp[s]+dp[s]*dp[to])%1000000007;
}
}
int main()
{
scanf("%I64d%I64d",&d,&n);
for(int i=1;i<=n;i++) scanf("%I64d",&V[i]);
for(int i=1;i<n;i++)
{
scanf("%I64d%I64d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=n;i++)
{
memset(dp,0,sizeof(dp));
dfs(i,-1,i);
ans=(ans+dp[i])%1000000007;
}
printf("%I64d\n",ans);
}