# include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 2;
int n, m, rt, a[N], x[N], tin[N], tout[N], timer, cur;
long long dp[505][N], dp2[505][N], pref[N], suff[N];
vector <int> g[N];
void dfs1(int v){
tin[v] = ++ timer;
for(int to : g[v]){
dfs1(to);
}
tout[v] = timer;
}
void dfs(int v){
for(int to : g[v]){
dfs(to);
}
dp[cur][tin[v]] = max(pref[tin[v] - 1] + suff[tout[v] + 1] + x[v], dp[cur][tin[v]]);
dp2[cur][tout[v]] = max(pref[tin[v] - 1] + suff[tout[v] + 1] + x[v], dp2[cur][tout[v]]);
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++){
int p;
cin >> p >> x[i];
if(!p)
rt = i;
else {
g[p].push_back(i);
}
}
dfs1(rt);
for(int i = 0; i <= m; i ++){
for(int j = 0; j < N; j ++)
dp[i][j] = dp2[i][j] = -1e18;
}
for(int i = 1; i <= n; i ++)
dp[1][i] = dp2[1][i] = x[i];
for(int i = 2; i <= m; i ++){
cur = i;
dfs(rt);
for(int j = 0; j <= n; j ++)
pref[j] = suff[j] = -1e18;
for(int j = 1; j <= n; j ++)
pref[j] = max(pref[j - 1], dp2[cur][j]);
for(int j = n; j >= 1; j --)
suff[j] = max(suff[j + 1], dp[cur][j]);
}
long long ans = 0;
for(int i = 1; i <= n; i ++)
ans = max(ans, dp[m][i]);
cout << ans << endl;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
19 ms |
20728 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |