一道树形dp,dp[u][k]表示第u个节点染k个黑点的最大值。
有点像树形背包,复杂度可以看作是枚举LCA 为 O(n^2)。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define LL long long
const int maxn = 2010;
int n,k,x,y,z,sz[maxn];
vector<int> f[maxn],g[maxn];
LL dp[maxn][maxn];
void dfs(int u,int fa)
{
sz[u]=1;dp[u][0]=dp[u][1]=0;
for(int i=0;i<f[u].size();i++)
{
int v=f[u][i];
if(v==fa) continue;
dfs(v,u);
sz[u]+=sz[v];
for(int j=sz[u];j>=0;j--)
{
for(int l=0;l<=min(sz[v],j);l++)
{
dp[u][j]=max(dp[u][j],dp[u][j-l]+((LL)(l*(k-l))+(LL)(sz[v]-l)*(LL)(n-k-(sz[v]-l)))*(LL)g[u][i]+dp[v][l]);
}
}
}
}
int main()
{
memset(dp,128,sizeof(dp));
scanf("%d%d",&n,&k);
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
f[x].push_back(y);f[y].push_back(x);
g[x].push_back(z);g[y].push_back(z);
}
dfs(1,0);
cout<<dp[1][k]<<endl;
return 0;
}
本文介绍了一种树形DP算法的应用实例,通过动态规划解决树结构中节点染色问题。文章详细展示了如何利用递归遍历及状态转移方程来求解最大值问题,并提供了完整的C++代码实现。

591

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



