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\n",f[0][m]);
return 0;
}