loj 2473. 「九省联考 2018」秘密袭击

题意

给出一棵树,每个节点有一个权值。问所有连通块中第k大元素的和模64123。
设最权值为W,n≤1666,W≤1666

分析

这一题正解有那么长!标程也是有那么长!
肝了好久肝不动果断转暴力

代码·

#include 

using namespace std;

const int N = 1710, mod = 64123;

int inc(int a, int b) 
{ 
    a += b; 
    return a >= mod ? a - mod : a; 
}

int n, k, d[N], rt, f[N][N]; 

vector < int > edge[N];

void dfs(int u, int fa, int *g) 
{
    if (d[u] > d[rt] || (d[u] == d[rt] && u > rt)) 
        for (int i = 1; i <= k; ++i)
            f[u][i] = g[i - 1];
    else
        for (int i = 1; i <= k; ++i)
            f[u][i] = g[i];
    for (auto v : edge[u])
        if (fa != v) dfs(v, u, f[u]);
    for (int i = 1; i <= k; ++i)
        g[i] = inc(g[i], f[u][i]);
}

int work(int u) 
{
    int cnt = 1;
    for (int i = 1; i <= n; ++i)
        if (d[i] > d[u] || (d[i] == d[u] && i > u))
            ++cnt;
    if (cnt < k) return 0;
    rt = u;
    memset(f[u], 0, sizeof f[u]);
    f[u][1] = 1;
    for (auto v : edge[u])
        dfs(v, u, f[u]);
    return 1ll * d[u] * f[u][k] % mod;
}

int main() 
{
    freopen("coat.in","r",stdin);
    freopen("coat.out","w",stdout);
    scanf("%d%d%*d", &n, &k);
    for (int i = 1; i <= n; ++i) scanf("%d", d + i);
    for (int i = 1; i < n; ++i) 
    {
        int u, v;
        scanf("%d%d", &u, &v);
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    int ans = 0;
    for (int i = 1; i <= n; ++i) ans = inc(ans, work(i));
    printf("%d\n", ans);
}

你可能感兴趣的:(dp)