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;
const int N = 3e5+5;
struct slope {
ll m, c;
priority_queue<ll> pq;
slope& operator+=(slope& ot) {
m += ot.m, c += ot.c;
if(pq.size() < ot.pq.size()) swap(pq, ot.pq);
while(!ot.pq.empty())
pq.push(ot.pq.top()), ot.pq.pop();
return *this;
}
};
slope f[N];
ll cost[N];
int n, m;
vector<int> adj[N];
void read() {
cin >> n >> m;
for(int i = 2; i <= n+m; i++) {
int p; cin >> p >> cost[i];
adj[p].push_back(i);
}
}
void dfs(int u) {
if(adj[u].empty()) {
f[u].m = 1, f[u].c = -cost[u];
f[u].pq.push(cost[u]);
f[u].pq.push(cost[u]);
return;
}
for(int v : adj[u]) {
dfs(v);
f[u] += f[v];
}
//reducing largest slope
while(f[u].m > 1) {
f[u].m -= 1;
f[u].c += f[u].pq.top();
f[u].pq.pop();
}
//adding parent edge
ll x = f[u].pq.top() + cost[u]; f[u].pq.pop();
ll y = f[u].pq.top() + cost[u]; f[u].pq.pop();
f[u].pq.push(x); f[u].pq.push(y);
f[u].c -= cost[u];
}
void solve() {
dfs(1);
ll ans = f[1].m * f[1].pq.top() + f[1].c;
cout << ans << '\n';
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
read();
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... |