joyOI 选课 【树形dp + 背包dp】

题目链接

选课

题解

基础背包树形dp

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<' '; puts("");
#define cls(s) memset(s,-0x3f3f3f3f,sizeof(s))
using namespace std;
const int maxn = 305,maxm = 100005,INF = 1000000000;
inline int read(){
	int out = 0,flag = 1; char c = getchar();
	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
	return out * flag;
}
int h[maxn],ne = 1;
struct EDGE{int to,nxt;}ed[maxm];
inline void build(int u,int v){
	ed[ne] = (EDGE){v,h[u]}; h[u] = ne++;
}
int n,m,val[maxn],f[maxn][maxn],fa[maxn];;
void dfs(int u){
	f[u][0] = 0;
	Redge(u){
		dfs(to = ed[k].to);
		for (int i = m; i >= 0; i--)
			for (int j = i; j >= 0; j--)
				f[u][i] = max(f[u][i],f[u][i - j] + f[to][j]);
	}
	if (u != 0)
		for (int i = m; i; i--)
			f[u][i] = f[u][i - 1] + val[u];
}
int main(){
	cls(f);
	n = read(); m = read();
	REP(i,n){
		fa[i] = read();
		val[i] = read();
		build(fa[i],i);
	}
	dfs(0);
	int ans = 0;
	for (int i = 0; i <= m; i++) ans = max(ans,f[0][i]);
	printf("%d\n",ans);
	return 0;
}

posted @ 2018-05-10 11:20  Mychael  阅读(174)  评论(0编辑  收藏  举报