Vijos P1180 选课(树形DP)
思路:
基本的树形DP,采用了树上泛化物品的并进行优化。dp[u][v] 代表 u 为根节点时,选择 v 个课程所能达到的最大学分。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 310;
int dp[MAXN][MAXN];
int pre[MAXN], val[MAXN];
int n;
void treedp(int u, int vol)
{
if (!vol)
return ;
for (int i = 1; i <= n; ++i)
{
if (pre[i] == u)
{
for (int v = 0; v <= vol; ++v)
dp[i][v] = dp[u][v];
treedp(i, vol - 1);
for (int v = vol; v >= 1; --v)
dp[u][v] = max(dp[u][v], dp[i][v-1] + val[i]);
}
}
}
int main()
{
int vol;
while (scanf("%d %d", &n, &vol) != EOF)
{
for (int i = 1; i <= n; ++i)
scanf("%d %d", &pre[i], &val[i]);
for (int j = 0; j <= vol; ++j)
dp[0][j] = 0;
treedp(0, vol);
printf("%d\n", dp[0][vol]);
}
return 0;
}
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------