https://www.luogu.com.cn/problem/CF486D
考虑树形DP
强制每个联通块的根为最大的那个数(如果有多个那么就是编号最大的那个)
然后枚举根就可以转移了
d
p
[
u
]
=
d
p
[
u
]
+
d
p
[
u
]
∗
d
p
[
v
]
dp[u]=dp[u]+dp[u]*dp[v]
dp[u]=dp[u]+dp[u]∗dp[v]
code:
#include<bits/stdc++.h>
#define N 2050
#define ll long long
#define mod 1000000007
using namespace std;
struct edge {
int v, nxt;
} e[N << 1];
int p[N], eid;
void init() {
memset(p, -1, sizeof p);
eid = 0;
}
void insert(int u, int v) {
e[eid].v = v;
e[eid].nxt = p[u];
p[u] = eid ++;
}
ll f[N];
int n, d, a[N];
void dfs(int u, int fa, int rt) {
f[u] = 1;
for(int i = p[u]; i + 1; i = e[i].nxt) {
int v = e[i].v;
if(v == fa) continue;
if((a[rt] > a[v] || (a[rt] == a[v] && rt > v)) && a[rt] - a[v] <= d) {
dfs(v, u, rt);
f[u] = (f[u] + f[u] * f[v]) % mod;
}
}
}
int main() {
init();
scanf("%d%d", &d, &n);
for(int i = 1; i <= n; i ++) scanf("%d", &a[i]);
for(int i = 1; i < n; i ++) {
int u, v;
scanf("%d%d", &u, &v);
insert(u, v), insert(v, u);
}
ll ans = 0;
for(int i = 1; i <= n; i ++) {
dfs(i, i, i);
ans = (ans + f[i]) % mod;
}
printf("%lld", ans);
return 0;
}