# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1005828 | omsincoconut | Fireworks (APIO16_fireworks) | C++17 | 2 ms | 12772 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
const ll MAXN = 3e5+5;
ll N, M, P[MAXN], C[MAXN];
vector<ll> child[MAXN];
struct MedianFinder{
ll n = 0;
priority_queue<ll> low, high;
void normalize() {
while (low.size() > (n>>1)) {
high.push(-low.top());
low.pop();
}
while (high.size() > (n>>1)) {
low.push(-high.top());
high.pop();
}
}
void insert(ll x) {
n++;
if (n == 1 || x < query()) low.push(x);
else high.push(-x);
normalize();
}
void merge(MedianFinder *target, ll offset = 0) {
while (!low.empty()) {
target->insert(low.top() + offset);
low.pop();
}
while (!high.empty()) {
target->insert(-high.top() + offset);
high.pop();
}
}
ll query() {
return low.top();
}
};
MedianFinder *dt[MAXN];
ll median[MAXN];
void dfs(ll u) {
dt[u] = new MedianFinder();
if (u > N) {
dt[u]->insert(0);
median[u] = 0;
return;
}
for (ll v : child[u]) dfs(v);
for (ll v : child[u]) dt[v]->merge(dt[u], C[v]);
median[u] = dt[u]->query();
/*ll nextc = child[u][0];
for (ll v : child[u]) if (dt[v]->n > dt[nextc]->n) nextc = v;
dt[u] = dt[nextc]*/
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> N >> M;
for (ll i = 2; i <= N+M; i++) cin >> P[i] >> C[i];
for (ll i = 2; i <= N+M; i++) child[P[i]].push_back(i);
C[1] = 0;
dfs(1);
ll ans = 0;
for (ll i = 2; i <= N+M; i++) {
ll df = median[P[i]] - median[i];
ans += abs(C[i] - df);
}
cout << ans;
return 0;
}
Compilation message (stderr)
# | 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... |