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;
#define pb push_back
#define sz(x) (int)x.size()
#define all(x) begin(x),end(x)
#define lb(x,y) lower_bound(all(x),y)-begin(x)
mt19937 rng;
void solve() {
int N, M; cin >> N >> M;
vector<vector<int>> adj(N);
vector<int> len(N + M, 0);
for (int i = 1; i < N + M; i++) {
int u; cin >> u; u--;
adj[u].pb(i);
cin >> len[i];
}
if (M == 0) {
cout << 0 << "\n";
return;
}
vector<priority_queue<ll>> x(N + M);
vector<ll> a(N + M, 0), b(N + M, 0);
for (int u = N + M - 1; u >= 0; u--) {
if (u >= N) {
x[u].push(len[u]);
x[u].push(len[u]);
a[u] = 1;
b[u] = -len[u];
} else {
for (int v : adj[u]) {
if (sz(x[v]) > sz(x[u])) {
swap(x[u], x[v]);
swap(a[u], a[v]);
swap(b[u], b[v]);
}
}
for (int v : adj[u]) {
if (x[v].empty()) continue;
while (!x[v].empty()) {
x[u].push(x[v].top());
x[v].pop();
}
a[u] += a[v];
b[u] += b[v];
}
while (a[u] > 1) {
a[u]--;
b[u] += x[u].top(); x[u].pop();
}
ll n2 = x[u].top(); x[u].pop();
ll n1 = x[u].top(); x[u].pop();
n1 += len[u];
n2 += len[u];
x[u].push(n1);
x[u].push(n2);
b[u] -= len[u];
}
}
cout << (x[0].top() + b[0]) << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());
solve();
return 0;
}
# | 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... |