二叉苹果树
题目描述
有一棵苹果树,如果树枝有分叉,一定是分二叉(就是说没有只有一个儿子的结点)
这棵树共有 N N N 个结点(叶子点或者树枝分叉点),编号为 1 ∼ N 1 \sim N 1∼N,树根编号一定是 1 1 1。
我们用一根树枝两端连接的结点的编号来描述一根树枝的位置。下面是一颗有 4 4 4 个树枝的树:
2 5
\ /
3 4
\ /
1
现在这颗树枝条太多了,需要剪枝。但是一些树枝上长有苹果。
给定需要保留的树枝数量,求出最多能留住多少苹果。
输入格式
第一行 2 2 2 个整数 N N N 和 Q Q Q,分别表示表示树的结点数,和要保留的树枝数量。
接下来 N − 1 N-1 N−1 行,每行 3 3 3 个整数,描述一根树枝的信息:前 2 2 2 个数是它连接的结点的编号,第 3 3 3 个数是这根树枝上苹果的数量。
输出格式
一个数,最多能留住的苹果的数量。
样例 #1
样例输入 #1
5 2
1 3 1
1 4 10
2 3 20
3 5 20
样例输出 #1
21
提示
1 ⩽ Q < N ⩽ 100 1 \leqslant Q < N \leqslant 100 1⩽Q<N⩽100,每根树枝上的苹果 ⩽ 3 × 1 0 4 \leqslant 3 \times 10^4 ⩽3×104。
#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 105;
struct edge {
int u;
int v;
int w;
int next;
}e[maxn << 1];
int cnt, head[maxn], sz[maxn], f[maxn][maxn];
int n, q;
void add_edge(int u, int v, int w) {
e[cnt++].u = u;
e[cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
}
void init() {
int a, b, c;
cin >> n >> q;
for (int i = 1; i < n; i++) {
cin >> a >> b >> c;
add_edge(a, b, c);
add_edge(b, a, c);
}
}
void dfs(int fa, int now) {
for (int i = head[now]; ~i; i = e[i].next) {
if (e[i].v == fa) continue;
int to = e[i].v;
dfs(now, to);
sz[now] += sz[to] + 1;
for(int j = q; j; j--)
for(int k = 0; k <= j - 1; k++)
f[now][j] = max(f[now][j], f[now][j - k - 1] + f[to][k] + e[i].w);
}
}
int main () {
memset(head, -1, sizeof(head));
init();
dfs(-1, 1);
cout << f[1][q] << endl;
return 0;
}