总结:
不知道啊做题全靠感觉瞎搞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("