# include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 2;
int n, m, rt, a[N], tin[N], tout[N], timer, cur;
long long dp[505][N], x[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][tout[v]] = max(dp[cur][tout[v]], dp[cur - 1][tin[v] - 1] + x[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][tout[i]] = max(x[i], dp[1][tout[i]]);
}
for(int i = 2; i <= m; i ++){
cur = i;
for(int j = 1; j <= n; j ++)
dp[i - 1][j] = max(dp[i - 1][j - 1], dp[i - 1][j]);
dfs(rt);
}
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 |
Correct |
12 ms |
12920 KB |
Output is correct |
2 |
Correct |
9 ms |
12920 KB |
Output is correct |
3 |
Correct |
29 ms |
34848 KB |
Output is correct |
4 |
Correct |
106 ms |
101032 KB |
Output is correct |
5 |
Correct |
121 ms |
124452 KB |
Output is correct |
6 |
Correct |
152 ms |
162104 KB |
Output is correct |
7 |
Correct |
1513 ms |
479952 KB |
Output is correct |
8 |
Correct |
1529 ms |
480080 KB |
Output is correct |
9 |
Runtime error |
455 ms |
525312 KB |
Execution killed with signal 9 (could be triggered by violating memory limits) |
10 |
Halted |
0 ms |
0 KB |
- |