题目分析
本题太经典,占坑以后一定写一下题解
代码
#include <cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
using namespace std;
const int maxn=203;
struct edge{int to,nt;}tree[maxn];
int nume;
int head[maxn];
int n,k;
int dp[maxn][maxn][2];
void add(int x,int y)
{
tree[nume].to=y;
tree[nume].nt=head[x];
head[x]=nume++;
}
void dfs(int x,int fa)
{
int son;
for(int i=head[x];i!=-1;i=tree[i].nt)
{
son=tree[i].to;
if(son==fa) continue;
dfs(son,x);
for(int j=k;j>=1;j--)
{
dp[x][j][1]=max(dp[x][j][1],dp[x][j-1][0]+dp[son][0][0]);
for(int l=2;l<=j;l++)
{
dp[x][j][0]=max(dp[x][j][0],dp[x][j-l][0]+dp[son][l-2][0]);
dp[x][j][1]=max(dp[x][j][1],dp[x][j-l][1]+dp[son][l-2][0]);
dp[x][j][1]=max(dp[x][j][1],dp[x][j-l][0]+dp[son][l-1][1]);
}
}
}
}
int main()
{
while(cin>>n>>k)
{
memset(head,0xff,sizeof head);
memset(dp,0,sizeof dp);
nume=0;
for(int i=1;i<=n;i++)
{
cin>>dp[i][0][0];
for(int j=0;j<=k;j++)
dp[i][j][0]=dp[i][j][1]=dp[i][0][0];
}
{
int x,y;
for(int i=1;i<n;i++)
{
cin>>x>>y;
add(x,y);
add(y,x);
}
}
dfs(1,-1);
cout<<max(dp[1][k][0],dp[1][k][1])<<endl;
}
return 0;
}

本文解析了一道经典的树形动态规划题目,通过详细的代码实现展示了如何利用递归深度优先搜索进行状态转移,以求解特定节点的最大得分。文章重点介绍了如何通过递归遍历子树来更新状态数组dp,并给出了完整的C++实现代码。
498

被折叠的 条评论
为什么被折叠?



