CH 5402 选课(分组背包+树形DP)

CH 5402 选课

VfWlU1.png



\(solution:\)

最近真是!越做题越觉得自己弱。这道题比较综合,它将有向树和背包结合,完全刷新世界观。首先我们可以发现这些课程显然不能随意调动顺序来背包,他们之间的关系可以用一颗有向树来表示(每一个节点代表一门课程,要选这门课程必须将它的祖先全都选了),但是这些树可能是分开的一片森林,所以我们可以建一个虚点将所有的没有父亲的根连在一起。这样我们发现我们直接从根开始背包是很没有思路的,后效性非常多。于是我们按照DP的一般规律从已知到未知,先从叶子节点开始由小树到大树。我们在某一棵子树上完全背包时就不必去管之前的必要课程,然后以每一个节点都来一次分组背包也满足有局部的最优解扩散到整体上去。



\(code:\)

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>

#define ll long long
#define db double
#define rg register int

using namespace std;

int n,m,ff,top;
int a[305];
int f[305][305];

int tou[305];
struct su{
    int to,next;
}b[305];

inline int qr(){
    register char ch; register bool sign=0; rg res=0;
    while(!isdigit(ch=getchar())) if(ch=='-')sign=1;
    while(isdigit(ch)) res=res*10+(ch^48),ch=getchar();
    return sign?-res:res;
}

inline void add(int x,int y){
    b[++top].to=y; b[top].next=tou[x]; tou[x]=top;
}

inline void dfs(int i){
    for(rg j=tou[i];j;j=b[j].next){
        rg to=b[j].to; dfs(to);
        for(rg p=m;p>0;--p)
            for(rg q=0;q<p;++q)
                f[i][p]=max(f[i][p],f[i][q]+f[to][p-q]);
    }if(i)for(rg k=m;k>0;--k)f[i][k]=f[i][k-1]+a[i];
}

int main(){
    //freopen(".in","r",stdin);
    //freopen(".out","w",stdout);
    n=qr(); m=qr();
    for(rg i=1;i<=n;++i)
        add(qr(),i),a[i]=qr();
    dfs(0); printf("%d\n",f[0][m]);
    return 0;
}

转载于:https://www.cnblogs.com/812-xiao-wen/p/11016409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值