#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 300; const int MAXM = 300; struct Tree { Tree *child, *next; int w; struct Answer { bool solved; int value; inline Answer(): solved(false) {} } ans[MAXM + 1]; inline Tree() {} inline Tree(Tree *parent, int w): w(w), next(parent->child) {} } trees[MAXN + 1]; int n, m; void addEdge(int parent, int child, int w) { trees[parent].child = new (&trees[child]) Tree(&trees[parent], w); } inline int solve (Tree *t, int m) { if (!t || m < 0) return 0; if (!t->ans[m].solved) { t->ans[m].value = 0; for (int i = 0; i < m; i++) { t->ans[m].value = max(t->ans[m].value, solve(t->child, i) + solve(t->next, m - i - 1) + t->w); } t->ans[m].value = max(t->ans[m].value, solve(t->next, m)); t->ans[m].solved = true; } return t->ans[m].value; } int main () { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { int parent, w; scanf("%d %d", &parent, &w); addEdge(parent, i, w); } printf("%d\n", solve(&trees[0], m + 1)); return 0; }
|