poj 2486 树形dp(给定步数 走一棵树,获得的节点值总和的最大值)

来源:互联网 发布:spyder导入tensorflow 编辑:程序博客网 时间:2024/05/16 02:11
#include<cstdio>#include<cstring>#define MAX(x,y) ((x)>(y)?(x):(y))struct node{int to,next;}e[2400];int cnt,n,k,head[220],dp[220][220][2],v[220];void add_edge(int from,int to){e[cnt].to=to;e[cnt].next=head[from];head[from]=cnt++;}void dfs(int u,int v){for(int i=head[u];i!=-1;i=e[i].next){int to=e[i].to;if(to==v)continue;dfs(to,u);for(int j=k;j>0;j--)for(int p=1;p<=j;p++){dp[u][j][0]=MAX(dp[u][j][0],dp[u][j-p][1]+dp[to][p-1][0]);if(p>1){dp[u][j][0]=MAX(dp[u][j][0],dp[u][j-p][0]+dp[to][p-2][1]);dp[u][j][1]=MAX(dp[u][j][1],dp[u][j-p][1]+dp[to][p-2][1]);}}}} int main(){while(~scanf("%d%d",&n,&k)){   for(int i=1;i<=n;i++)   {     scanf("%d",&v[i]);     for(int j=0;j<=k;j++)     dp[i][j][0]=dp[i][j][1]=v[i];       }       cnt=0;   memset(head,-1,sizeof(head));    for(int i=1;i<n;i++)   {      int a,b;      scanf("%d%d",&a,&b);      add_edge(a,b);      add_edge(b,a);       }       dfs(1,-1);       printf("%d\n",dp[1][k][0]);    }}

0 0
原创粉丝点击