「一本通」树形dp学习笔记

本文是关于树形dp的学习笔记,通过多个LOJ题目进行实战解析,包括二叉苹果树、选课、战略游戏等,讲解了不同类型的树形dp问题及解题策略,如儿子遍历、儿子继承父亲状态等,涉及dfs和记忆化搜索的应用。
摘要由CSDN通过智能技术生成

总结:

不知道啊做题全靠感觉瞎搞2333
一种是儿子遍历完了传给父亲,例如求树的重心树的最长链balabala,一种是儿子继承父亲状态,有一些就是纯粹的一道dp给你套棵树,实现一般都是dfs/记忆化搜索


loj#10153. 「一本通 5.2 例 1」二叉苹果树

https://loj.ac/problem/10153
dfs整棵树出来 然后左右儿子选还是不选直接记忆化搜索乱搞ac

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct nodee
{
	int x,y,c,next;
}a[210];
struct node
{
	int l,r;
	node()
	{
		l=r=-1;
	}
}tr[110];
int last[110],len,f[110][110],n,m;
void build(int x,int y,int c)
{
	len++;
	a[len].x=x;a[len].y=y;a[len].c=c;a[len].next=last[x];last[x]=len;
}
void dfs(int x,int fa)
{
	for (int k=last[x];k;k=a[k].next)
	{
		int y=a[k].y;
		if (y!=fa)
		{
			f[y][1]=a[k].c;
			if (tr[x].l==-1) tr[x].l=y;
			else tr[x].r=y;
			dfs(y,x);
		}
	}
}
int treedp(int x,int k)
{
	if (f[x][k]!=-1) return f[x][k];
	int maxx=0;
	for (int i=0;i<=k-1;i++)
	{
		int lc=0,rc=0;
		if (tr[x].l!=-1) lc=treedp(tr[x].l,i);
		if (tr[x].r!=-1) rc=treedp(tr[x].r,k-1-i);
		maxx=max(maxx,lc+rc);
	}
	f[x][k]=maxx+f[x][1];
	return f[x][k];
}
int main()
{
	scanf("%d%d",&n,&m);
	for (int i=1;i<n;i++)
	{
		int x,y,c;
		scanf("%d%d%d",&x,&y,&c);
		build(x,y,c); build(y,x,c);
	}
	memset(f,-1,sizeof(f));
	for (int i=1;i<=n;i++) f[i][0]=0;
	f[1][1]=0;
	dfs(1,0);
	printf("%d\n",treedp(1,m+1));
	return 0;
}

loj#10154. 「一本通 5.2 例 2」选课

https://loj.ac/problem/10154
多叉树转二叉树(左儿子是真正的儿子 右儿子是兄弟)后也是直接上记忆化搜索乱搞 注意选右儿子的话自己选不选都行

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct node
{
	int l,r,c,last;//左儿子是真正的儿子 右儿子是兄弟 
	node()
	{
		l=r=-1;
		c=last=0;
	}
}tr[1100];
int f[1100][1100],n,m;
int treedp(int x,int k)
{
	if (f[x][k]!=-1) return f[x][k];
	int maxx=0;
	for (int i=0;i<=k;i++)
	{
		int ls=0,rs=0;
		if (tr[x].l!=-1&&i!=k) ls=f[tr[x].l][k-i-1]=treedp(tr[x].l,k-i-1);//自己的儿子要选了自己
		if (tr[x].r!=-1) rs=f[tr[x].r][i]=treedp(tr[x].r,i);
		if (i==k) maxx=max(maxx,rs);
		else maxx=max(maxx,ls+rs+tr[x].c);
	}
	f[x][k]=maxx; return maxx;
}
int main()
{
	scanf("%d%d",&n,&m);
	memset(f,-1,sizeof(f));
	for (int i=1;i<=n;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		if (tr[x].l==-1) tr[x].l=i,tr[x].last=i;
		else tr[tr[x].last].r=i,tr[x].last=i;
		tr[i].c=y; f[i][0]=0;
	}
	printf("
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值