#include <bits/stdc++.h>
#define ll long long
#define pii pair<int, int>
#define xx first
#define yy second
#define pb push_back
#define MAXN 200010
#define MAXM 510
#define MAXX 100000010
using namespace std;
ll n, m, p[MAXN], w[MAXN], dp[MAXN][MAXM];
bool bio[MAXN];
vector<int> g[MAXN];
void merge(int u, int v)
{
ll pomoc[MAXM];
for (int i=0; i<=m; i++) pomoc[i]=dp[u][i];
for (int i=0; i<=m; i++)
for (int j=0; i+j<=m; j++)
if (i+j<=m) pomoc[i+j]=max(pomoc[i+j], dp[u][i]+dp[v][j]);
for (int i=0; i<=m; i++) dp[u][i]=pomoc[i];
}
void dfs(int u)
{
bio[u]=true;
for (int i=0; i<=m; i++) dp[u][i]=-MAXX;
dp[u][0]=0;
for (auto v:g[u])
{
if (!bio[v])
{
dfs(v);
}
}
for (auto v:g[u])
{
if (v==p[u]) continue;
merge(u, v);
}
dp[u][1]=max(dp[u][1], w[u]);
///cout<<u<<":"<<endl;
///for (int i=0; i<=m; i++) cout<<dp[u][i]<<" ";
///cout<<endl;
}
int main(){
cin>>n>>m;
int koren=1;
for (int i=1; i<=n; i++)
{
cin>>p[i]>>w[i];
if (p[i]==0) { koren=i; continue; }
g[p[i]].pb(i); g[i].pb(p[i]);
}
dfs(koren);
cout<<dp[koren][m];
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
4948 KB |
Output is correct |
2 |
Incorrect |
4 ms |
4948 KB |
Output isn't correct |
3 |
Correct |
3 ms |
5332 KB |
Output is correct |
4 |
Correct |
33 ms |
40800 KB |
Output is correct |
5 |
Correct |
46 ms |
45340 KB |
Output is correct |
6 |
Correct |
66 ms |
45304 KB |
Output is correct |
7 |
Execution timed out |
2110 ms |
301948 KB |
Time limit exceeded |
8 |
Execution timed out |
2094 ms |
312080 KB |
Time limit exceeded |
9 |
Execution timed out |
2075 ms |
152136 KB |
Time limit exceeded |
10 |
Execution timed out |
2081 ms |
107260 KB |
Time limit exceeded |