二叉苹果树 - 洛谷https://www.luogu.com.cn/problem/P2015
一道很好的树上dp题,其中siz数组可以没有就是稍微优化一下而已
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <unordered_map>
#include <cmath>
#include <map>
#include <cctype>
#include <cstdlib>
#include <deque>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1000010;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
int n, m;
int head[MAXN];
int nxt[MAXN];
int cost[MAXN];
int ver[MAXN];
int f[150][150];
int cnt;
inline void add(int x, int y, int c) {
ver[++cnt] = y;
nxt[cnt] = head[x];
cost[cnt] = c;
head[x] = cnt;
}
int siz[MAXN];
void dp(int p, int fa) {
for (int i = head[p]; i; i = nxt[i]) {
int v = ver[i];
if (v == fa)
continue;
dp(v, p);
siz[p] += siz[v] + 1;
for (int j = min(siz[p], m); j; j--) {
for (int k = min(siz[v], j - 1); k >= 0; k--) {
f[p][j] = max(f[p][j], f[p][j - k - 1] + f[v][k] + cost[i]);
}
}
}
}
int main() {
int x, y, c;
scanf("%d %d", &n, &m);
for (int i = 1; i < n; i++) {
scanf("%d %d %d", &x, &y, &c);
add(x, y, c);
add(y, x, c);
}
dp(1, 0);
printf("%d", f[1][m]);
return 0;
}