标签:des style blog http io color ar os sp
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5506 Accepted Submission(s): 3274
和前面两题一样、= =
#include <iostream> #include <cstring> #include <cstdio> using namespace std; #define N 210 struct Edge { int next,to; }edge[N*N/2]; int head[N<<1],tot; int m,n; int val[N]; int dp[N][N]; //dp[i][j]表示用攻占以i根节点的j个城堡的获得的最大宝物数 void init() { tot=0; memset(head,-1,sizeof(head)); memset(dp,0,sizeof(dp)); } void add(int x,int y) { edge[tot].to=y; edge[tot].next=head[x]; head[x]=tot++; } void dfs(int u) { dp[u][1]=val[u]; for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].to; dfs(v); for(int j=m;j>=1;j--) { for(int k=0;k<j;k++) { dp[u][j]=max(dp[u][j],dp[u][j-k]+dp[v][k]); } } } } int main() { while(scanf("%d%d",&n,&m), n||m) { init(); for(int i=1;i<=n;i++) { int x; scanf("%d%d",&x,&val[i]); add(x,i); } m++; //虚拟了节点0,将森林化为树 dfs(0); cout<<dp[0][m]<<endl; } return 0; }
树形DP [HDU 1561] The more, The Better
标签:des style blog http io color ar os sp
原文地址:http://www.cnblogs.com/hate13/p/4094132.html