树形dp问题(持续更新中...)

  1. hdu 1561
    代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int M = 220;
int n, m, v[M];
vector<int>son[M];
int dp[M][M];

void dfs(int num, int left)
{
    int i, j, k, len = son[num].size();
    dp[num][1] = v[num];
    for (i = 0; i < len; i++)
    {
        if (left > 1)   dfs(son[num][i], left-1);
        for (j = left; j >= 1; j--)
        {
            for (k = 1; k <= j; k++)
            {
                dp[num][j+1] = max(dp[num][j+1], dp[num][j+1-k] + dp[son[num][i]][k]);
            }
        }
    }
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
#endif
    int i, j;
    while(cin >>n >> m, n||m)
    {
        memset(v, 0, sizeof(v));
        memset(dp, 0, sizeof(dp));
        for (i = 0; i <= n; i++)    son[i].clear();
        for (i = 1; i <= n; i++)
        {
            scanf("%d%d", &j, &v[i]);
            son[j].push_back(i);
        }
        dfs(0, m+1);
        printf("%d\n", dp[0][m+1]);
    }

    return 0;
}

你可能感兴趣的:(dp,DFS)