vector<int> son[maxn], sson[maxn]; int n, m; int a[maxn], c[maxn], aa[maxn], cc[maxn], bel[maxn], cnt; int dp[maxn][maxm];
voiddfs(int u){ for (int i = 0; i < cc[u]; i++) dp[u][i] = -9999999; for (int i = cc[u]; i <= m; i++) dp[u][i] = aa[u]; for (auto v : sson[u]) { // write(v); dfs(v); for (int i = m; i >= cc[u] + cc[v]; i--) { for (int j = cc[v]; j + cc[u] <= i; j++) { dp[u][i] = max(dp[u][i], dp[u][i - j] + dp[v][j]); } } } }
stack<int> st; bool in_st[maxn]; int dfn_cnt, dfn[maxn], low[maxn];
voidtarjan(int u){ dfn[u] = low[u] = ++dfn_cnt; st.emplace(u); in_st[u] = true; for (auto v : son[u]) { if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } elseif (in_st[v]) { low[u] = min(low[u], dfn[v]); } } if (dfn[u] == low[u]) { int v; ++cnt; do { v = st.top(); st.pop(); in_st[v] = false; bel[v] = cnt; } while (v != u); } }
bool book[maxn];
intmain(){ read(n); read(m); for (int i = 1; i <= n; i++) { read(c[i]); } for (int i = 1; i <= n; i++) { read(a[i]); } for (int i = 1; i <= n; i++) { int s; read(s); if (s) son[s].emplace_back(i); } for (int i = 1; i <= n; i++) { if (!dfn[i]) tarjan(i); } for (int i = 1; i <= n; i++) { aa[bel[i]] += a[i]; cc[bel[i]] += c[i]; for (int x : son[i]) { if (bel[i] != bel[x]) { sson[bel[i]].emplace_back(bel[x]); book[bel[x]] = true; } } } for (int i = 1; i <= cnt; i++) if (!book[i]) sson[0].emplace_back(i); dfs(0); write(dp[0][m]); return0; }