#include <bits/stdc++.h>
#define fr first
#define sc second
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define pb push_back
#define pw(x) (1ll << x)
#define vec vector
#define sz(x) (int)((x).size())
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
template <typename T> inline bool umin (T &a, const T &b) { if (a > b) { a = b; return 1; } return 0; }
template <typename T> inline bool umax (T &a, const T &b) { if (a < b) { a = b; return 1; } return 0; }
const int N = 2e5 + 100;
const int M = 505;
vector <int> g[N];
int dp[N][M], siz[N], m, a[N];
inline void sizes (int v, int pr) { siz[v] = 1; for (auto u : g[v]) if (u != pr) sizes(u, v), siz[v] += siz[u]; }
inline void dfs (int v, int pr) {
for (auto u : g[v]) if (u != pr) dfs(u, v);
for (auto u : g[v]) if (u != pr) {
for (int i = min(siz[v], m); i >= 0; --i) {
for (int j = min(siz[u], m - i); j >= 0 && i + j <= m; --j) {
umax(dp[v][i + j], dp[v][i] + dp[u][j]);
}
}
}
umax(dp[v][1], a[v]);
}
inline void solve () {
int n; cin >> n >> m;
int rt = -1, p;
for (int i = 0; i < n; ++i) {
cin >> p >> a[i];
if (!p) { rt = i; continue; }
--p;
g[i].pb(p); g[p].pb(i);
}
sizes(rt, rt); dfs(rt, rt);
cout << dp[rt][m];
}
signed main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else
//freopen("biorobot.in", "r", stdin);
//freopen("biorobot.out", "w", stdout);
#endif
int t = 1; // cin >> t;
while (t--) solve();
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
4948 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Correct |
3 ms |
5156 KB |
Output is correct |
4 |
Correct |
17 ms |
22996 KB |
Output is correct |
5 |
Correct |
19 ms |
25200 KB |
Output is correct |
6 |
Correct |
21 ms |
25292 KB |
Output is correct |
7 |
Correct |
363 ms |
304840 KB |
Output is correct |
8 |
Correct |
361 ms |
304852 KB |
Output is correct |
9 |
Correct |
522 ms |
369956 KB |
Output is correct |
10 |
Correct |
682 ms |
408028 KB |
Output is correct |