#include <bits/stdc++.h>
using namespace std;
int n,m,inp[200005];
int piv,sz[200005],a[200005];
vector<int> g[200005];
int root;
int dfs(int x){
int num = ++piv;
a[num] = inp[x];
sz[num] = 1;
for(int &i : g[x]){
sz[num] += dfs(i);
}
return sz[num];
}
int dp[2][200005];
void mx(int&a, int b) { a=max(a, b); }
int main() {
ios::sync_with_stdio(0);cin.tie(0);
int N, K, r;
cin>>N>>K;n=N,m=K;
int D[2][200004], F[N+1], G[N+1]{}, W[N+1];
for(int i=1; i<=N; i++) {
int p;
cin>>p>>W[i];inp[i]=W[i];
if(p) F[i]=G[p], G[p]=i,g[p].push_back(i);
else root=r=i;
}
dfs(root);
for (int i=1; i<=m; i++) {
dp[i%2][n+1] = -1e9;
for (int j=n; j; j--) {
dp[i%2][j] = max(dp[i%2][j+1],dp[(i-1)%2][j+sz[j]] + a[j]);
}
}
int n[2]{}, d=0;
function<int(int)> cg=[&](int i) {
int p=n[d];
for(int e=G[i]; e; e=F[e]) {
d^=1;
int m=cg(e);
d^=1;
int q=n[d^1]-=m, j=min(n[d]-p+m, K);
while(n[d]<p+j) D[d][n[d]++]=0;
while(--j) for(int k=min(m, j); k--;)
mx(D[d][p+j], D[d][p+j-k-1]+D[d^1][q+k]);
for(int k=0; k<m; k++) mx(D[d][p+k], D[d^1][q+k]);
}
if(p==n[d]) D[d][n[d]++]=W[i];
else mx(D[d][p], W[i]);
return n[d]-p;
};
cout<<(N<=200000 ? dp[m%2][1] : D[0][cg(r)-1])<<'\n';
}
Compilation message
biochips.cpp: In function 'int main()':
biochips.cpp:25:12: warning: 'r' may be used uninitialized in this function [-Wmaybe-uninitialized]
25 | int N, K, r;
| ^
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
5 ms |
6604 KB |
Output is correct |
2 |
Incorrect |
4 ms |
6476 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |