#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#define INF 0x3f3f3f3f
#define rep0(i, n) for (int i = 0; i < n; i++)
#define rep1(i, n) for (int i = 1; i <= n; i++)
#define rep_0(i, n) for (int i = n - 1; i >= 0; i--)
#define rep_1(i, n) for (int i = n; i > 0; i--)
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#define mem(x, y) memset(x, y, sizeof(x))
/**
题目大意
有n个节点 各赋有权值 获得各节点的权值可能需要先获得另一节点的权值
求在n个结点中取m个最多能获得多少权值
思路
两结点之间的依赖关系转化为父子之间的有向边
没有依赖的节点作为0的子节点
*/
#define MAXN 200 + 10
using namespace std;
typedef long long LL;
vector<int> g[MAXN];
LL V[MAXN], dp[MAXN][MAXN];
void dfs(int u, int m)
{
if (m == 0)
return;
for (int i = 0; i < g[u].size(); i++)
{
int v = g[u][i]; //枚举父亲节点的各子结点
dfs(v, m - 1);
for (int s = m; s >= 0; s--) //父节点以下分配容量为s
{
for (int s1 = m - 1; s1 >= 0; s1--) //子节点以下容量为s1
if (s - s1 - 1 >= 0)
dp[u][s] = MAX(dp[u][s], dp[u][s - s1 - 1] + dp[v][s1] + V[v]);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int n, m, a, b;
while (scanf("%d %d", &n, &m) != EOF && n)
{
mem(dp, 0);
for (int i = 0; i <= n; i++)
g[i].clear();
for (int i = 1; i <= n; i++)
{
scanf("%d %d", &a, &b);
g[a].push_back(i);
V[i] = b;
}
dfs(0, m);
printf("%lld\n", dp[0][m]);
}
return 0;
}
hdu1561_The more, The Better(树形DP/背包)
最新推荐文章于 2018-08-07 20:10:39 发布