【算法笔记】 树形DP算法总结

定义:树形DP也叫树状DP,即在树上进行的DP,是DP中较为复杂一类

1:主体

即like拓扑排序,从叶子节点向上更新其父节点,从而进行dp,确保先更新的子节点去更新其父节点,一般使用dfs形式:

void dfs(ll u,ll fa)
{
	dp[u]=1;
	for(auto c:G[u])
	{
		if(c!=fa)
		{
			dfs(c,u);
			dp[u]+=dp[c];
		}
	}
}

【例1.2】洛谷P1352 没有上司的舞会

//P1352 没有上司的舞会
//2024.3.27 12:38

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const ll N = 500005;
#define mod 1000000007
#define inf 1e18
#define YES cout<<"YES"<<'\n';
#define NO cout<<"NO"<<'\n';
#define lc p<<1
//左子节点
#define rc p<<1|1

vector<ll>a[N],sz(N),f(N),g(N),rot(N);
void dfs(ll u,ll fa)
{
	//sz[u]=1;
	for(auto c:a[u])
	{
		if(c!=fa)
		{
			dfs(c,u);
			f[u]+=g[c];//选择了u就不能选择他儿子
			g[u]+=max(g[c],f[c]);//不选择u也可以不选择儿子,也可以选择
		}
	}
}
void solve()
{
	ll n;cin>>n;
	for(ll i=1;i<=n;i++) cin>>sz[i],f[i]=sz[i];//初始化每个人的兴趣度
	for(ll i=1;i<n;i++)
	{
		ll x,y;cin>>x>>y;
		a[x].push_back(y);
		a[y].push_back(x);
		rot[y]++;
	}
	ll d=0;
	for(ll i=1;i<=n;i++)
	{
		if(!rot[i])
		{
			d=i;//找boss
			break;
		}
	}
	dfs(d,0);
	cout<<max(g[d],f[d])<<'\n';
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	//ll t;cin>>t;
	//while(t--) 
	solve();
	return 0;
}

2:树形背包

3:换根DP

相关推荐

  1. 算法笔记树形DP算法总结

    2024-03-30 23:20:04       44 阅读
  2. 算法刷题day39:树形DP

    2024-03-30 23:20:04       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-30 23:20:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-30 23:20:04       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-30 23:20:04       82 阅读
  4. Python语言-面向对象

    2024-03-30 23:20:04       91 阅读

热门阅读

  1. Linux中定时任务的配置及注意事项

    2024-03-30 23:20:04       37 阅读
  2. 微机原理与应用精炼100题

    2024-03-30 23:20:04       32 阅读
  3. 钉钉机器人发送自定义消息 PHP 干货

    2024-03-30 23:20:04       45 阅读
  4. 创建springboot项目的两种方式

    2024-03-30 23:20:04       39 阅读
  5. openGauss 客户端工具DataStudio

    2024-03-30 23:20:04       46 阅读
  6. leetcode283-Move Zeroes

    2024-03-30 23:20:04       40 阅读
  7. python——遍历网卡并禁用/启用

    2024-03-30 23:20:04       39 阅读
  8. 使用Python创建井字棋游戏

    2024-03-30 23:20:04       39 阅读
  9. 服务器大请求体问题定位

    2024-03-30 23:20:04       38 阅读