Codeforces Round #277 (Div. 2) D. Valid Sets 树形DP

链接:

http://codeforces.com/contest/486/problem/D

题意:

给你一棵树,从中选一棵子树,满足

S is non-empty.

S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.

.

题解:

从每个节点dfs,但是要避免重复,代码中的continue就是避免重复

代码:

31 int d, n;
32 int a[MAXN];
33 VI G[MAXN];
34 int dp[MAXN];
35 
36 void dfs(int u, int fa, int rt) {
37     dp[u] = 1;
38     rep(i, 0, G[u].size()) {
39         int v = G[u][i];
40         if (v == fa) continue;
41         if (a[v] > a[rt] + d) continue;
42         if (a[v] < a[rt]) continue;
43         if (a[v]==a[rt] && v < rt) continue;
44         dfs(v, u, rt);
45         dp[u] = 1LL * dp[u] * (dp[v] + 1) % MOD;
46     }
47 }
48 
49 int main() {
50     ios::sync_with_stdio(false), cin.tie(0);
51     cin >> d >> n;
52     rep(i, 1, n + 1) cin >> a[i];
53     rep(i, 1, n) {
54         int u, v;
55         cin >> u >> v;
56         G[u].pb(v);
57         G[v].pb(u);
58     }
59     int ans = 0;
60     rep(i, 1, n + 1) {
61         memset(dp, 0, sizeof(dp));
62         dfs(i, 0, i);
63         ans = (ans + dp[i]) % MOD;
64     }
65     cout << ans << endl;
66     return 0;
67 }

 

posted @ 2017-08-05 12:23  Flowersea  阅读(129)  评论(0编辑  收藏  举报