#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define N 200005
#define M 505
int dp[N][M], pr[N], n, m, s[N], cnt, in[N], out[N], l, r, now, ans;
vector <int> child[N], ve;
void dfs(int x){
if (!child[x].size()) cnt++;
in[x] = cnt;
for (auto a : child[x])
dfs(a);
ve.pb(x);
out[x] = cnt;
}
int main (){
cin >> n>> m;
for (int i = 1;i <= n;i++){
cin >> pr[i]>> s[i];
child[pr[i]].pb(i);
}
dfs(child[0][0]);
for (auto x : ve){
l = in[x];
r = out[x];
for (int i = 0;i <= m;i++)
dp[r][i] = max(dp[r][i], dp[r - 1][i]);
for (int i = 1;i <= min(l, m);i++)
dp[r][i] = max(dp[r][i], dp[l - 1][i - 1] + s[x]);
}
for (int i = 1;i <= cnt;i++)
ans = max(ans, dp[i][m]);
cout << ans;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
4984 KB |
Output is correct |
2 |
Correct |
6 ms |
5108 KB |
Output is correct |
3 |
Correct |
7 ms |
5260 KB |
Output is correct |
4 |
Correct |
26 ms |
14356 KB |
Output is correct |
5 |
Correct |
31 ms |
18928 KB |
Output is correct |
6 |
Correct |
33 ms |
18960 KB |
Output is correct |
7 |
Correct |
616 ms |
301532 KB |
Output is correct |
8 |
Correct |
618 ms |
303112 KB |
Output is correct |
9 |
Correct |
692 ms |
368292 KB |
Output is correct |
10 |
Correct |
853 ms |
407840 KB |
Output is correct |