1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| #include <cstdio> #include <vector> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } typedef long long LL; const int N = 2e3 + 10, mod = 1e9 + 7; int n, d, w[N], f[N]; vector <int> g[N]; void adj (int &x) { x += x >> 31 & mod; } bool cmp (int a, int b) { return w[a] > w[b] || (w[a] == w[b] && a < b); } int dfs (int x, int fa, int &st) { f[x] = 1; for (int i : g[x]) if (i ^ fa && cmp(st, i) && w[st] - w[i] <= d) f[x] = (LL)f[x] * (dfs(i, x, st) + 1) % mod; return f[x]; } int main () { read(d), read(n); for (int i = 1; i <= n; i++) read(w[i]); for (int i = 1, a, b; i < n; i++) { read(a), read(b); g[a].push_back(b); g[b].push_back(a); } int res = 0; for (int i = 1; i <= n; i++) adj(res += dfs(i, 0, i) - mod); write(res); return 0; }
|