#include "bits/stdc++.h"
using namespace std;
void solve() {
int n, m;
cin >> n >> m;
vector<vector<int>> g(n);
vector<int> a(n);
int rt;
for (int i = 0; i < n; i++) {
int p;
cin >> p >> a[i];
p--;
if (p == -1) {
rt = i;
} else {
g[p].push_back(i);
}
}
vector<int> tin(n), tout(n);
vector<vector<pair<int, int>>> go(n);
int T = 0;
auto dfs = [&] (auto& dfs, int v) -> void {
tin[v] = T++;
for (auto u : g[v]) {
dfs(dfs, u);
}
tout[v] = T;
go[tin[v]].push_back({tout[v], a[v]});
};
dfs(dfs, rt);
vector<vector<int>> dp(n + 1, vector<int> (m + 1, -(int) 1e9));
dp[0][0] = 0;
for (int i = 0; i < n; i++) {
for (auto [r, x] : go[i]) {
for (int j = 0; j < m; j++) {
dp[r][j + 1] = max(dp[r][j + 1], dp[i][j] + x);
}
}
for (int j = 0; j <= m; j++) {
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);
}
}
cout << dp.back().back();
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--) {
solve();
}
}
Compilation message
biochips.cpp: In function 'void solve()':
biochips.cpp:32:8: warning: 'rt' may be used uninitialized in this function [-Wmaybe-uninitialized]
32 | dfs(dfs, rt);
| ~~~^~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
1 ms |
336 KB |
Output is correct |
2 |
Correct |
1 ms |
336 KB |
Output is correct |
3 |
Correct |
1 ms |
336 KB |
Output is correct |
4 |
Correct |
6 ms |
3920 KB |
Output is correct |
5 |
Correct |
6 ms |
4688 KB |
Output is correct |
6 |
Correct |
8 ms |
5712 KB |
Output is correct |
7 |
Correct |
198 ms |
195144 KB |
Output is correct |
8 |
Correct |
201 ms |
195144 KB |
Output is correct |
9 |
Correct |
312 ms |
302292 KB |
Output is correct |
10 |
Correct |
447 ms |
405576 KB |
Output is correct |