# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1123693 | math_rabbit_1028 | Tree (IOI24_tree) | C++20 | 0 ms | 0 KiB |
#include "tree.h"
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
int n;
int par[202020];
vector<int> child[202020];
ll w[202020];
void init(vector<int> P, vector<int> W) {
n = (int)P.size();
for (int i = 0; i < n; i++) {
par[i] = P[i];
child[par[i]].push_back(i);
}
for (int i = 0; i < n; i++) w[i] = W[i];
}
pll range[202020];
ll res[202020];
ll minabs(ll l, ll r) {
if (l <= 0 && r >= 0) return 0;
if (r < 0) return r;
if (l > 0) return l;
}
void update(int v) {
ll mns = 0, mxs = 0;
for (int u : child[v]) {
mns += range[u].first;
mxs += range[u].second;
}
for (int u : child[v]) {
range[u].first = max(range[u].first, range[v].first + range[u].second - mxs);
range[u].second = min(range[u].second, range[v].second + range[u].first - mns);
}
}
long long query(int L, int R) {
ll ans = 0;
priority_queue<pll> pq;
for (int i = 0; i < n; i++) {
ll m = child[i].size();
range[i] = {L-m*R, R-m*L};
pq.push({w[i], i});
}
while (!pq.empty()) {
int v = pq.top().second;
pq.pop();
res[v] = minabs(range[v].first, range[v].second);
pll temp = {range[v].second - res[v], res[v] - range[v].first};
range[v] = {res[v], res[v]};
ans += w[v] * abs(res[v]);
update(v);
int p = par[v];
if (p < 0) continue;
range[p].first += temp.first;
range[p].second -= temp.second;
update(p);
}
return ans;
}