HDU 1011(树形dp)

#include
#include
#include
#include
#include
#include
using namespace std;

int dp[105][105];
int cost[105];
int value[105];
vector<int> list[105];
int N, M;
bool visited[105];

void dfs(int father)
{
    int temp = (cost[father] + 19) / 20;
    int len = list[father].size();
    for (int i = temp; i <= M; i++)
        dp[father][i] = value[father];
    visited[father] = true;
    for (int i = 0; i int child = list[father][i];
        if (visited[child])
            continue;
        dfs(child);
        for (int j = M; j >= temp; j--)
        {
            for (int k = 1; k <= j - temp; k++)
            {
                dp[father][j] = max(dp[father][j], dp[father][j - k] + dp[child][k]);
            }

        }

    }
}
int main()
{
    while (scanf("%d%d", &N, &M))
    {
        for (int i = 0; i <= N; i++)
        {
            list[i].clear();
        }
        if (N == -1 && M == -1)
            return 0;
        memset(dp, 0, sizeof(dp));
        memset(value, 0, sizeof(value));
        memset(cost, 0, sizeof(cost));
        memset(visited, false, sizeof(visited));
        for (int i = 1; i <= N; i++)
        {
            cin >> cost[i] >> value[i];
        }
        int a, b;
        for (int i = 1; i <= N - 1; i++)
        {
            cin >> a >> b;
            list[b].push_back(a);
            list[a].push_back(b);
        }
        if (M == 0) { printf("0\n"); continue; }
        dfs(1);
        cout << dp[1][M] << endl;
    }
    return 0;
}

你可能感兴趣的:(ACM_HDU)