#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <deque>
#include <stack>
#include <cmath>
#include <math.h>
#include <array>
#include <random>
#include <bitset>
#include <climits>
#include <cstring>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define endl '\n'
#define mod 1000000007
#define INF 0x3f3f3f3f
// #define int long long
template <class x>
using ordered_set = tree<x, null_type, less<x>, rb_tree_tag, tree_order_statistics_node_update>;
typedef pair<int, int> ipair;
static inline int read()
{
int x = 0;char ch = getchar();
while (ch < '0' || ch>'9') ch = getchar();
while (ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + (ch ^ 48), ch = getchar();
return x;
}
static inline void print(const int &x) {
if (x > 9) print(x / 10);
putchar('0' + x % 10);
}
vector<int> adj[200005];
int dp[200005][505], sub[200005], la[200005];
int n, m;
static inline void dfs(int x)
{
sub[x]=1;
for(auto i : adj[x])
{
dfs(i);
sub[x] += sub[i];
for(int k=min(m,sub[i]);k >= 1;k--)
for(int j = min(k, sub[x]);j>=0;j--) dp[x][k] = max(dp[x][k], dp[i][k-j]+dp[x][j]);
}
dp[x][1] = max(dp[x][1], la[x]);
}
signed main()
{
cin.tie(0) -> sync_with_stdio(0);
cin >> n>>m;
int r=0;
for(int i = 1;i <= n;i++)
{
int x, w;
cin >> x >> w;
la[i]=w;
if(x==0) {r=i;continue;}
adj[x].push_back(i);
}
dfs(r);
cout << dp[r][m];
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |