#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 200005;
int N;
vector<int> tree[MAXN];
int weight[MAXN];
bool isLeaf[MAXN];
int leafCount[MAXN];
vector<pair<ll, ll>> segments; // {a, b} means a * L + b * R
void dfs_mark_leaves_and_count(int u) {
isLeaf[u] = true;
leafCount[u] = 0;
for (int v : tree[u]) {
isLeaf[u] = false;
dfs_mark_leaves_and_count(v);
leafCount[u] += leafCount[v];
}
if (isLeaf[u]) leafCount[u] = 1;
}
// Recursive decomposition
void decompose(int u) {
int k = leafCount[u];
if (isLeaf[u]) {
segments.push_back({1LL * k * weight[u], 0}); // contributes k*L*W[u]
return;
}
// If kL - R > 0, we pay (kL - R) * W[u], which is a = k*W[u], b = -W[u]
segments.push_back({1LL * k * weight[u], -1LL * weight[u]});
for (int v : tree[u]) {
decompose(v);
}
}
void init(vector<int> P, vector<int> W) {
N = P.size();
for (int i = 0; i < N; ++i) {
tree[i].clear();
isLeaf[i] = false;
}
for (int i = 1; i < N; ++i) {
tree[P[i]].push_back(i);
}
for (int i = 0; i < N; ++i) weight[i] = W[i];
dfs_mark_leaves_and_count(0);
segments.clear();
decompose(0);
}
ll query(int L, int R) {
ll res = 0;
for (auto& seg : segments) {
res += seg.first * L + seg.second * R;
}
return res;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |