[Algorithm template] tree backpack

[Algorithm template] tree backpack

Tree 01 backpack

Common tree backpacks and backpack 01 is different in that there are mutual dependencies between items. Select a necessary condition for the son items are selected all of his ancestors.

We consider dp[i][j]represents the first iin the sub-tree points, it took jthe maximum weight capacity can get one.

Fake code:

for(int i=1;i<=son;i++){//枚举所有儿子
  dfs(son[i]);//先处理儿子
  for(int j1=m;j1>=0;j1--){//枚举当前点用掉了多少容量(正着枚举会变成完全背包)
    for(int j2=0;j2<=j1;j2++){//枚举这个儿子分配多少
      dp[i][j1]=max(dp[i][j1],dp[i][j1-j2]+dp[son[i]][j2]);//更新状态
    }
  }
}

Obviously, the complexity is \ (O (n * m ^ 2) \) a.

Tree backpack special case of optimization

When the volume of the article are all 1, we can optimize it to (O (n ^ 2) \ ) \ complexity.

Code from lsj grandfather of:

At first glance no different from the original root, but note that, for each pair of points it will only be enumerated to time in their LCA. Think about why you can own.

Complexity \ (n-2 ^ \) .

example

Tree 01 backpack optimization

There is a way to optimize it to (n * m \) \ complexity.

Gugu Gu

Reference material

Tree backpack bounds Optimization

[Algorithm] [Auditorium, University of Electronic Science and Technology] [ACM] tree knapsack problem

Optimization of the tree to the backpack 01 O (n * m)

Guess you like

Origin www.cnblogs.com/GavinZheng/p/11519540.html
Recommended