#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;
int n, m, p[MAXN], w[MAXN], dp[MAXN][MAXM];
bool bio[MAXN];
vector<int> g[MAXN];
void merge(int u, int v)
{
int 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; 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];
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
2 ms |
4948 KB |
Output is correct |
2 |
Incorrect |
2 ms |
4948 KB |
Output isn't correct |
3 |
Correct |
2 ms |
5204 KB |
Output is correct |
4 |
Correct |
63 ms |
23144 KB |
Output is correct |
5 |
Correct |
83 ms |
25380 KB |
Output is correct |
6 |
Correct |
118 ms |
25444 KB |
Output is correct |
7 |
Execution timed out |
2076 ms |
125228 KB |
Time limit exceeded |
8 |
Execution timed out |
2069 ms |
124400 KB |
Time limit exceeded |
9 |
Execution timed out |
2079 ms |
48344 KB |
Time limit exceeded |
10 |
Execution timed out |
2053 ms |
40100 KB |
Time limit exceeded |