# 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], 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][v] = max(pref[tin[v] - 1] + suff[tout[v] + 1] + x[v], dp[cur][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] = -1e18;
}
for(int i = 1; i <= n; i ++)
dp[1][i] = x[i];
for(int i = 2; i <= m; i ++){
cur = i;
dfs(rt);
for(int j = 0; j <= n + 1; j ++)
pref[j] = suff[j] = -1e18;
for(int j = 1; j <= n; j ++){
pref[ tout[j] ] = max(pref[ tout[j] ], dp[cur][j]);
suff[ tin[j] ] = max(suff[ tin[j] ], dp[cur][j]);
}
for(int j = 1; j <= n; j ++)
pref[j] = max(pref[j - 1], pref[j]);
for(int j = n; j >= 1; j --)
suff[j] = max(suff[j + 1], suff[j]);
}
long long ans = 0;
for(int i = 1; i <= n; i ++)
ans = max(ans, pref[i]);
cout << ans << endl;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
10 ms |
12920 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |