二叉苹果树

题目地址:

https://ac.nowcoder.com/acm/problem/50505

基本思路:

树形背包的过程,设表示以为根有条树枝的子树上的最大的苹果数是多少,
对于每棵子树,我们每次转移时可以得到如下的转移方程:

也就是说我们可以从已经处理的子树上选择个树枝的子树,再在新子树上选择个树枝的子树,
然后加上当前连着这条子树的树枝,就能组成以为根有条树枝的子树了。

基本思路:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false); cin.tie(0)
#define int long long
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 110;
struct Edge{
    int to,next,w;
}edge[maxn << 1];
int n,q,cnt,head[maxn];
void add_edge(int u,int v,int w){
  edge[++cnt].next = head[u];
  edge[cnt].to = v;
  edge[cnt].w = w;
  head[u] = cnt;
}
int dp[maxn][maxn];
void dfs(int u,int par) {
  sz[u] = 1;
  for(int i = head[u] ; i != -1; i = edge[i].next){
    int to = edge[i].to;
    if(to == par) continue;
    dfs(to,u);
    for(int j = n ; j >= 1 ; j--){
      for(int k = 0 ; k < j ; k++) {
        dp[u][j] = max(dp[u][j], dp[u][k] + dp[to][j - k - 1] + edge[i].w);
      }
    }
  }
}
signed main() {
  IO;
  cnt = 0;
  mset(head,-1);
  cin >> n >> q;
  for(int i = 1 ; i < n ; i++){
    int u,v,w;
    cin >> u >> v >> w;
    add_edge(u,v,w);
    add_edge(v,u,w);
  }
  dfs(1,0);
  cout << dp[1][q] << '\n';
  return 0;
}