其他分享
首页 > 其他分享> > CF486D Valid Sets

CF486D Valid Sets

作者:互联网

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;
}

标签:rt,int,ans,dfs,CF486D,Valid,eid,Sets,dp
来源: https://blog.csdn.net/qq_38944163/article/details/120693305