#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int maxn = 2e5 + 5;
int n, m, root, par[maxn], val[maxn], in[maxn], out[maxn], dp[maxn][505], timer = 0;
vector<int> graph[maxn], euler;
void dfs(int u) {
in[u] = timer++; euler.push_back(u);
for(int &v : graph[u]) dfs(v);
out[u] = timer - 1;
}
inline bool anc(int u, int v) {
return in[u] <= in[v] && out[v] <= out[u];
}
int main() {
cin >> n >> m;
for(int i=1; i<=n; i++) {
cin >> par[i] >> val[i];
if(par[i]) graph[par[i]].push_back(i);
else root = i;
}
dfs(root);
if(n <= 20) {
int ans = 0;
for(int s=0; s<(1<<n); s++) {
if(__builtin_popcount(s) != m) continue;
int res = 0, ok = 1;
vector<int> vec;
for(int i=0; i<n; i++)
if(s & (1 << i)) vec.push_back(i+1), res += val[i+1];
for(int i=0; i<vec.size(); i++)
for(int j=i+1; j<vec.size(); j++)
if(anc(vec[i], vec[j]) || anc(vec[j], vec[i])) ok = 0;
if(ok) ans = max(ans, res);
}
cout << ans << '\n';
return 0;
}
for(int i=n-1; i>=0; i--) {
for(int j=0; j<=m; j++) {
dp[i][j] = max(dp[i+1][j], dp[out[euler[i]]+1][j]);
if(j) dp[i][j] = max(dp[i][j], dp[out[euler[i]]+1][j-1] + val[euler[i]]);
}
}
cout << dp[1][m] << '\n';
return 0;
}
Compilation message
biochips.cpp: In function 'int main()':
biochips.cpp:39:27: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
39 | for(int i=0; i<vec.size(); i++)
| ~^~~~~~~~~~~
biochips.cpp:40:33: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
40 | for(int j=i+1; j<vec.size(); j++)
| ~^~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
2 ms |
10844 KB |
Output is correct |
2 |
Incorrect |
1 ms |
10844 KB |
Output isn't correct |
3 |
Correct |
3 ms |
10844 KB |
Output is correct |
4 |
Correct |
8 ms |
27044 KB |
Output is correct |
5 |
Correct |
11 ms |
29016 KB |
Output is correct |
6 |
Correct |
10 ms |
29020 KB |
Output is correct |
7 |
Correct |
261 ms |
302924 KB |
Output is correct |
8 |
Correct |
268 ms |
303048 KB |
Output is correct |
9 |
Correct |
357 ms |
367564 KB |
Output is correct |
10 |
Correct |
456 ms |
405084 KB |
Output is correct |