P2015 二叉苹果树
P2015 二叉苹果树
树形 \(DP\) , 虽然非常简单...但是我写了好久, 就因为预处理...日!
它是把贡献放在边上了, 我们做一个转化, 把边权转化成点权, 然后 \(Q++\) , 这样就好处理多了.
\(code:\)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int read() {
int x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
const int N = 205;
int n, q, f[N][N];
int tot, to[N], val[N], nxt[N], head[N];
void add(int u, int v, int w) {
to[++tot] = v, val[tot] = w, nxt[tot] = head[u], head[u] = tot;
}
void dfs(int x, int fa) {
for (int i = head[x]; i; i = nxt[i]) {
int y = to[i];
if (y == fa) continue;
f[y][1] = val[i];
dfs(y, x);
for (int j = q; j >= 1; j--) {
for (int k = 1; k < j; k++) {
f[x][j] = max(f[x][j], f[y][k] + f[x][j - k]);
}
}
}
}
int main() {
n = read(), q = read() + 1;
for (int i = 1; i < n; i++) {
int u = read(), v = read(), w = read();
add(u, v, w); add(v, u, w);
}
dfs(1, 0);
printf("%d", f[1][q]);
return 0;
}
看不见我看不见我看不见我