Luogu P2014_Problem Transformation_Set of Templates

Templates available https://blog.csdn.net/jay__bryant/article/details/80213774


This topic: Forest structure, including point weights, select a number of points to maximize the weight


Problem transformation:

(1) Add a new node 0 as the root node

(2) The parent node of a point with no parent is 0

(3) Convert the point weight of each point to the edge weight of the edge connected to the parent node

(4) Then the problem is transformed into a model of the template

******************************************************************************

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 333;

int to[maxn<<1], next[maxn<<1], val[maxn<<1];
int head[maxn], tot;

int n, m;
int dp[maxn][maxn];

int dfs (int u, int fa);
void merge_(int u, int v, int w);

intmain()
{
    int i, j, u, w;
    memset(dp, 0, sizeof(dp));
    memset(head, 0, sizeof(head));
    scanf("%d %d", &n, &m);
    to = 0;
    for(i = 1; i <= n; ++i)
    {
        scanf("%d %d", &u, &w);
        merge_(u, i, w);
        merge_(i, u, w);
    }
    dfs(0, 0);
    printf("%d\n", dp[0][m]);
    return 0;
}

int dfs (int u, int fa)
{
    int i, j, k, son = 0;
    for(i = head[u]; i; i = next[i])
    {
        int v = to[i], value = val[i];
        if(v == fa) continue;
        son += dfs(v, u) + 1;
        for(j = min(son, m); j; --j)
            for(k = j; k; --k)
                dp[u][j] = max(dp[u][j], dp[u][j-k]+dp[v][k-1]+value);
    }
    return son;
}

void merge_(int u, int v, int w)
{
    ++to;
    to [tot] = v;
    val[tot] = w;
    next[tot] = head[u];
    head[u] = tot;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325726028&siteId=291194637