#include #include using namespace std; const int MAXN = 300 + 5; typedef struct { int left, right; int score; } node; node tree[MAXN]; int mem[MAXN][MAXN]; int N, M; void insert(int current, int head) { tree[current].right = tree[head].left; tree[head].left = current; } int dfs(int node, int slots) { if (node < 0 || !slots) { return 0; } else if (!node) { // Root node return dfs(tree[node].left, slots); } if (mem[node][slots] > -1) { return mem[node][slots]; } mem[node][slots] = dfs(tree[node].right, slots); // When ignore this node for (int i = 1; i <= slots; i++) { int other = dfs(tree[node].left, i - 1) + dfs(tree[node].right, slots - i) + tree[node].score; mem[node][slots] = max(mem[node][slots], other); } return mem[node][slots]; } int main() { // Init cin >> N >> M; memset(tree, -1, sizeof tree); memset(mem, -1, sizeof mem); for (int i = 1; i <= N; i++) { int depends, c; cin >> depends >> c; insert(i, depends); tree[i].score = c; } // Calculating! printf("%d", dfs(0, M)); }