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;
using lint = long long;
using pint = pair<int, int>;
#define x first
#define y second
const int maxn = 300004;
int N, M;
vector<pint> g[maxn];
struct func {
priority_queue<lint> neg;
priority_queue<lint, vector<lint>, greater<lint> > pos;
lint mn = 0;
void balance() {
while (neg.top() > pos.top()) {
lint x = neg.top(), y = pos.top();
neg.pop(); pos.pop();
pos.push(x); neg.push(y);
mn += x - y;
}
}
void add(lint a, lint b, lint c) {
neg.push(a);
pos.push(b);
mn += c;
balance();
}
void process(lint x) {
lint b = neg.top() + x, c = pos.top() + x;
while (!pos.empty()) pos.pop();
neg.pop();
neg.push(b);
pos.push(c);
}
} *b[maxn];
void dfs(int x) {
func *f = new func();
for (pint i : g[x]) if (!g[i.x].empty()) {
dfs(i.x);
b[i.x]->process(i.y);
if (f->neg.size() < b[i.x]->neg.size()) f = b[i.x];
}
b[x] = f;
for (pint i : g[x]) if (f != b[i.x]) {
if (!g[i.x].empty()) {
func *g = b[i.x];
while (!g->neg.empty()) f->neg.push(g->neg.top()), g->neg.pop();
while (!g->pos.empty()) f->pos.push(g->pos.top()), g->pos.pop();
f->mn += g->mn;
f->balance();
} else f->add(i.y, i.y, 0);
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> N >> M;
for (int i=2; i<=N+M; i++) {
int x, y;
cin >> x >> y;
g[x].emplace_back(i, y);
}
dfs(1);
cout << b[1]->mn << '\n';
}
# | 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... |