#include<iostream>
#include<algorithm>
#include<cstring>
#include<numeric>
#include<vector>
using namespace std;
typedef long long ll;
const int N = 2e5 + 8;
int n, m, a[N];
vector<int> g[N];
int tme, tin[N], tout[N];
int inv[N];
void dfs(int u) {
inv[tin[u] = ++tme] = u;
for (int v : g[u]) dfs(v);
tout[u] = tme;
}
int dp[N][502];
int main() {
cin.tie(NULL)->sync_with_stdio(false);
cin >> n >> m;
for (int i = 1, p; i <= n; ++i) {
cin >> p >> a[i];
g[p].push_back(i);
}
dfs(g[0][0]);
memset(dp[n + 1], 0x80, sizeof(dp[n + 1]));
dp[n + 1][0] = 0;
for (int i = n; i; --i) {
copy(dp[i + 1], dp[i + 1] + m + 1, dp[i]);
for (int j = 1; j <= m; ++j)
dp[i][j] = max(dp[i][j], dp[tout[inv[i]] + 1][j - 1] + a[inv[i]]);
}
cout << (dp[1][m] < 0 ? -1 : dp[1][m]) << '\n';
}
/** /\_/\
* (= ._.)
* / >0 \>1
**/
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
5032 KB |
Output is correct |
2 |
Correct |
3 ms |
5016 KB |
Output is correct |
3 |
Correct |
3 ms |
5196 KB |
Output is correct |
4 |
Correct |
13 ms |
22732 KB |
Output is correct |
5 |
Correct |
14 ms |
25000 KB |
Output is correct |
6 |
Correct |
15 ms |
25036 KB |
Output is correct |
7 |
Correct |
193 ms |
299688 KB |
Output is correct |
8 |
Correct |
183 ms |
299684 KB |
Output is correct |
9 |
Correct |
224 ms |
363880 KB |
Output is correct |
10 |
Correct |
268 ms |
401700 KB |
Output is correct |