#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for (int i = a; i < b; i++)
typedef vector<int> vi;
const int INF=1e9;
const int MAXN = 200005;
int n,m,root;
vi g[MAXN];
int par[MAXN],a[MAXN],st[MAXN],fin[MAXN];
int tim = 0;
int dp[MAXN][505];
void dfs(int u){
st[u] = tim;
for(auto v:g[u]) dfs(v);
for(int i=1;i<=m;i++){
dp[tim+1][i] = max(dp[tim][i],dp[st[u]][i-1]+a[u]);
}
tim++;
}
signed main(){
cin >> n >> m;
for(int i=1;i<=n;i++){
int p;
cin >> p >> a[i];
if(!p) root = i;
else g[p].push_back(i);
}
for(int i=1;i<=m;i++) dp[0][i] = -INF;
dfs(root);
cout << dp[n][m] << "\n";
}
/*
int val[200001], m, t;
vector<int> g[200001];
int dp[200001][501], par[200001];
void dfs(int c)
{
par[c] = t;
for(int e : g[c]) dfs(e);
for(int i=1;i<=m;i++)
dp[t+1][i] = max(dp[t][i],dp[par[c]][i-1]+val[c]);
t++;
}
int main()
{
int n, r;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
int p;
scanf("%d%d",&p,val+i);
if(!p) r = i;
else g[p].push_back(i);
}
for(int i=1;i<=m;i++) dp[0][i] = -1e9;
dfs(r);
printf("%d\n",dp[n][m]);
}
*/
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
3 ms |
4940 KB |
Output is correct |
2 |
Correct |
3 ms |
4940 KB |
Output is correct |
3 |
Correct |
3 ms |
5196 KB |
Output is correct |
4 |
Correct |
17 ms |
22752 KB |
Output is correct |
5 |
Correct |
17 ms |
24908 KB |
Output is correct |
6 |
Correct |
17 ms |
24940 KB |
Output is correct |
7 |
Correct |
259 ms |
298688 KB |
Output is correct |
8 |
Correct |
272 ms |
298884 KB |
Output is correct |
9 |
Correct |
291 ms |
363248 KB |
Output is correct |
10 |
Correct |
378 ms |
400984 KB |
Output is correct |