正题
评测记录:https://www.luogu.org/problemnew/show/P2014
题目大意
有n门课程,每个课程有不同的学分和前修课,必须学了前修课才可以学这门。
只能修m门,求最大学分
解题思路
背包的思想,套一个树形dp。
code
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
struct tree{int to,next;
}a[200001];
int n,c[301],w,ls[301],f[301][301],tot,rx,m;
void addl(int x,int y)
{a[++tot].to=y;a[tot].next=ls[x];ls[x]=tot;
}//加边
void dp(int x)
{f[x][0]=0;for(int i=ls[x];i;i=a[i].next){int y=a[i].to;dp(y);for(int j=m;j>=0;j--)for(int t=j;t>=0;t--)if(j-t>=0)f[x][j]=max(f[x][j],f[x][j-t]+f[y][t]);//背包}if(x!=0)for(int i=m;i>0;i--)f[x][i]=f[x][i-1]+c[x];//计算当前这门课的得分
}
int main()
{scanf("%d%d",&n,&m);for (int i=1;i<=n;i++){ scanf("%d%d",&rx,&c[i]);addl(rx,i);}dp(0);printf("%d",f[0][m]);
}