[luogu 2014][tyvj 1051]选课{背包类树形DP}

题目

https://www.luogu.org/problemnew/show/P2014
http://www.joyoi.cn/problem/tyvj-1051


解题思路

F[x][t] F [ x ] [ t ] 表式在以 x x 为根的子树中选t门课能够获得的最高学分,设 x x 的子节点集合为Son(x),子节点个数 p=|Son(x)| p = | S o n ( x ) | F[x][t]=0 F [ x ] [ t ] = 0

F[x][t]=max{pi=1F[yi][ci]} | i=1pci=t1 F [ x ] [ t ] = m a x { ∑ i = 1 p F [ y i ] [ c i ] }   |   ∑ i = 1 p c i = t − 1


代码

#include<cstdio>
#include<algorithm>
using namespace std; 
struct node{int y,next;}a[1001];
int n,m,len,last[1001],f[1001][1001],c[1001]; 
void add(int x,int y)
{ a[++len]=(node){y,last[x]};last[x]=len;}
void dp(int x)
{
    f[x][0]=0; 
    for (int i=last[x];i;i=a[i].next)
    {
        int y=a[i].y; dp(y); 
        for (int t=m;t>=0;t--)
         for (int j=t;j>=0;j--)
          if (t-j>=0) f[x][t]=max(f[x][t],f[x][t-j]+f[y][j]);
    }
    if (x!=0) 
     for (int t=m;t>0;t--) f[x][t]=f[x][t-1]+c[x]; 
}
int main()
{
    scanf("%d%d",&n,&m); 
    int x;
    for (int i=1;i<=n;i++)
    {
         scanf("%d%d",&x,&c[i]);
         add(x,i); 
    }
    dp(0); 
    printf("%d",f[0][m]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值