题目链接:Codeforces 486D Valid Sets
题目大意:给定一棵树,每个节点有个权值,现在要选定一些节点,要求非空,并且maxVal-minVal不大于d。问说有多
少种选择方法。
解题思路:枚举每个节点作为根节点,默认根节点为权值最大的节点,然后各个孩子节点用乘法原理即可。
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
const int maxn = 2005;
int N, D, W[maxn];
vector<int> G[maxn];
ll dfs(int u, int f, int rt) {
int n = G[u].size();
ll ret = 1;
for (int i = 0; i < n; i++) {
int v = G[u][i];
if (v == f || W[rt] < W[v] || (W[rt] == W[v] && v > rt) || W[rt] - W[v] > D)
continue;
ret = ret * (dfs(v, u, rt) + 1) % mod;
}
return ret;
}
int main () {
scanf("%d%d", &D, &N);
for (int i = 1; i <= N; i++)
scanf("%d", &W[i]);
int u, v;
for (int i = 1; i < N; i++) {
scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
ll ans = 0;
for (int i = 1; i <= N; i++)
ans = (ans + dfs(i, -1, i)) % mod;
printf("%lld\n", ans);
return 0;
}
Codeforces 486D Valid Sets(暴力)
原文:http://blog.csdn.net/keshuai19940722/article/details/41077133