#include <bits/stdc++.h>
#define fastInp ios_base::sync_with_stdio(0); cin.tie(0);
#define fr first
#define sc second
#define pii pair<int, int>
#define pb push_back
#define all(s) s.begin(), s.end()
#define szof(s) (int)s.size()
using namespace std;
const int MAXN = (int)2e5 + 5;
vector <int> g[MAXN];
int cost[MAXN];
int tin[MAXN], tout[MAXN], tiktak = 0;
void precalc(int v, int par) {
tin[v] = ++tiktak;
for (int to : g[v]) {
if (to != par) {
precalc(to, v);
}
}
tout[v] = tiktak;
}
bool father(int a, int b) {
return (tin[a] <= tin[b] && tout[b] <= tout[a]);
}
signed main() {
fastInp;
int n, m;
cin >> n >> m;
assert(n <= 20); // wtf
int root = -1;
for (int i = 1; i <= n; i++) {
int par, x;
cin >> par >> x;
if (!par) {
root = i;
} else {
g[par].pb(i);
g[i].pb(par);
}
cost[i] = x;
}
precalc(root, -1);
int ans = 0;
for (int mask = 0; mask < (1 << n); mask++) {
int cnt = __builtin_popcount(mask);
if (cnt != m) {
continue;
}
vector <int> vec;
for (int i = 0; i < n; i++) {
if (mask & (1 << i)) {
vec.pb(i + 1);
}
}
bool ok = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (i == j) {
continue;
}
ok &= (!father(vec[i], vec[j]));
}
}
if (ok) {
int sum = 0;
for (int el : vec) {
sum += cost[el];
}
ans = max(ans, sum);
}
}
cout << ans << endl;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
4 ms |
5120 KB |
Output is correct |
2 |
Correct |
4 ms |
5100 KB |
Output is correct |
3 |
Runtime error |
10 ms |
10112 KB |
Execution killed with signal 6 |
4 |
Halted |
0 ms |
0 KB |
- |