hdu 1011 Starship Troopers(树形dp)

http://acm.hdu.edu.cn/showproblem.php?pid=1011

dp[i][j]表示在第i个位置放j个trooper,然后又该节点分配给子节点后所能得到的最大brains;

状态转移方程dp[i][j]=max(dp[i][j],dp[i][j-k]+dp[son[i]][k]);

从叶子节点往根节点递推。。。

View Code
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#define maxn 107
using namespace std;
struct node
{
int bugs;
int brain;
}tagp[maxn];
vector<int>g[maxn];//尝试stl的vector
int n,m,dp[maxn][maxn],visit[maxn];

void dfs(int pos)
{
int i,j;
visit[pos] = true;
int nleast = (tagp[pos].bugs + 19)/20;//一个对付20个,计算最少需要多少个trooper
for (i = nleast; i <= m; ++i)
{
dp[pos][i] = tagp[pos].brain;
}
for (i = 0; i < g[pos].size(); ++i)//递归的求解
{
int p = g[pos][i];
if(visit[p])
continue;
dfs(p);
for (j = m; j >= nleast; --j)
{
for (int k = 1; k + j <= m; ++k)
if(dp[p][k])
dp[pos][j+k] = max(dp[pos][j+k],dp[pos][j]+dp[p][k]);
}
}
}
int main()
{
int i,a,b;
while (scanf("%d%d",&n,&m))
{
if (n == -1&&m == -1)
break;
for (i = 1; i <= n; ++i)
{
scanf("%d%d",&tagp[i].bugs,&tagp[i].brain);
g[i].clear();//更新
}
for (i = 0; i < n-1; ++i)
{
scanf("%d%d",&a,&b);
g[a].push_back(b);//建图
g[b].push_back(a);
}
if (m == 0)//注意这里优化处理
{
puts("0");
continue;
}
memset(visit,false,sizeof(visit));
memset(dp,0,sizeof(dp));
dfs(1);
printf("%d\n",dp[1][m]);
}
return 0;
}



你可能感兴趣的:(oop)