现在的位置: 首页 > 综合 > 正文

HDU – 1561(简单树形背包)

2019年04月03日 ⁄ 综合 ⁄ 共 842字 ⁄ 字号 评论关闭
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const int inf  = 100000;
const int maxn = 205;
int n,m,head[maxn],len;
struct node{
 int to,next;
}tree[maxn*2];
void init(){
  memset(head,-1,sizeof(head));
  len = 0;
}
void add_eadge(int u,int v){
  tree[len].to = v;
  tree[len].next = head[u];
  head[u] = len++;
}
int d[maxn][maxn],temp[maxn],w[maxn];
void dfs(int root,int f){
  for(int i=0;i<=m;i++)
    d[root][i] = 0;
  for(int i=head[root];i!=-1;i=tree[i].next){
    if(tree[i].to == f) continue;
    int p = tree[i].to;
    dfs(p,root);
    for(int j=0;j<=m;j++) temp[j]=d[root][j];
    for(int j=1;j<=m;j++)
        for(int k=1;k<=j;k++)
          d[root][j]=max(d[root][j],temp[j-k]+d[p][k-1]+w[p]);
  }
}
int main()
{
    while(scanf("%d %d",&n,&m)==2){
      if(!n&&!m) break;
      init();
      for(int i=1;i<=n;i++){
        int x,y;
        scanf("%d %d",&x,&y);
        add_eadge(x,i);
        add_eadge(i,x);
        w[i] = y;
      }
      w[0] = 0;
      dfs(0,-1);
      printf("%d\n",d[0][m]);
    }
    return 0;
}

抱歉!评论已关闭.