zoukankan      html  css  js  c++  java
  • CH 5402 选课(分组背包+树形DP)

    CH 5402 选课



    $ 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
    ",f[0][m]);
    	return 0;
    }
    
    
  • 相关阅读:
    集合set
    字典
    元组
    列表
    for循环
    Windows调试2.异常产生详细流程
    双机环境搭建
    Windows调试1.WinDbg基本使用-异常基础知识
    PE基础7-HOOK练习
    PE基础6_远程线程注入-HOOK(消息-InLine-IAT)
  • 原文地址:https://www.cnblogs.com/812-xiao-wen/p/11016409.html
Copyright © 2011-2022 走看看