This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/**
* code generated by JHelper
* More info: https://github.com/AlexeyDmitriev/JHelper
* @author memikakizaki
*/
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
using namespace std;
#define long long long
const long MOD = 1e9+7, LINF = 1e18 + 1e16;
const int INF = 1e9+1;
const double EPS = 1e-10;
const int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
class Fireworks {
int n, m;
vector<vector<pair<int,long> > > g;
vector<priority_queue<long> > pq;
vector<long> val;
void print_pq_increasing(priority_queue<long>& pq) {
vector<long> res;
while(!pq.empty()) {
res.push_back(pq.top());
pq.pop();
}
reverse(res.begin(), res.end());
for(long x: res) pq.push(x), cout << x << ' ';
cout << endl;
}
void dfs(int u, long wpar) {
long cnt = 0;
for(auto pr: g[u]) {
int v;
long w;
tie(v, w) = pr;
dfs(v, w);
if(pq[u].empty()) {
val[u] += val[v];
} else if(pq[v].top() > pq[u].top()) {
val[u] += val[v] + 1ll * cnt * abs(pq[v].top() - pq[u].top());
} else {
val[u] += val[v] + abs(pq[u].top() - pq[v].top());
}
if(pq[v].size() > pq[u].size()) {
swap(pq[u], pq[v]);
}
while(!pq[v].empty()) pq[u].push(pq[v].top()), pq[v].pop();
++cnt;
}
long r;
while(cnt--) {
r = pq[u].top();
pq[u].pop();
val[u] -= 1ll * cnt * (r - pq[u].top()); // already --
}
if(!g[u].empty()) {
long l = pq[u].top();
pq[u].pop();
pq[u].push(l + wpar);
pq[u].push(r + wpar);
// cout << "l " << l << ' ' << "r " << r << endl;
} else {
pq[u].push(wpar);
pq[u].push(wpar);
}
// cout << "node " << u << endl;
// cout << "val " << val[u] << endl;
// for(auto pr:g[u]) {
// int v; tie(v, ignore) = pr;
//// cout << v << ' ' << val[v] << endl;
// }
// print_pq_increasing(pq[u]);
// cout << endl;
}
public:
void solve(istream& cin, ostream& cout) {
cin >> n >> m;
n += m;
g = vector<vector<pair<int,long> > >(n);
pq = vector<priority_queue<long> >(n);
val = vector<long>(n);
for(int i = 1, p, c; i < n; i++) {
cin >> p >> c;
g[p-1].emplace_back(i, c);
}
dfs(0, 0);
// for(int i = 0; i < n; i++) cout << i << ' ' << val[i] << endl;
cout << val[0] << endl;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
Fireworks solver;
std::istream& in(std::cin);
std::ostream& out(std::cout);
solver.solve(in, out);
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... |