#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
const int maxm = 5e2+10;
const int inf = 1e9+10;
typedef pair<int, int> pii;
struct T
{
int in, out, v;
} t[maxn];
int n, m, root;
int num[maxn], tt;
int dp[maxn][maxm], in[maxn], out[maxn];
vector<int> grafo[maxn], vv[maxn];
void dfs(int u, int p)
{
in[u] = ++tt;
for (auto v: grafo[u])
if (v != p)
dfs(v, u);
out[u] = tt;
vv[tt].push_back(u);
}
int main(void)
{
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
int p;
cin >> p >> num[i];
if (p)
{
grafo[i].push_back(p);
grafo[p].push_back(i);
}
if (!p) root = i;
}
dfs(root, 0);
for (int i = 0; i <= n; i++)
{
dp[i][0] = 0;
for (int j = 1; j <= m; j++)
dp[i][j] = -inf;
}
for (int i = 1; i <= n; i++)
{
for (auto u: vv[i])
for (int j = 1; j <= m; j++)
dp[i][j] = max({dp[i][j], dp[i-1][j], num[u]+dp[in[u]-1][j-1]});
if (vv[i].size() == 0)
for (int j = 1; j <= m; j++)
dp[i][j] = dp[i-1][j];
}
int ans = 0;
for (int i = 1; i <= n; i++)
ans = max(ans, dp[i][m]);
cout << ans << "\n";
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
9 ms |
9848 KB |
Output is correct |
2 |
Correct |
10 ms |
9848 KB |
Output is correct |
3 |
Correct |
10 ms |
9976 KB |
Output is correct |
4 |
Correct |
31 ms |
28152 KB |
Output is correct |
5 |
Correct |
33 ms |
30456 KB |
Output is correct |
6 |
Correct |
34 ms |
30456 KB |
Output is correct |
7 |
Correct |
420 ms |
317560 KB |
Output is correct |
8 |
Correct |
427 ms |
317688 KB |
Output is correct |
9 |
Correct |
558 ms |
384888 KB |
Output is correct |
10 |
Correct |
630 ms |
424528 KB |
Output is correct |