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;
const int maxn = 3e5;
priority_queue<long long> dp[maxn];
long long val[maxn];
int slope[maxn];
vector<int> g[maxn];
int par[maxn], c[maxn];
/*void print(int v) {
vector<long long> res;
{
auto tmp = down[v];
while (!tmp.empty()) {
res.emplace_back(tmp.top());
tmp.pop();
}
reverse(res.begin(), res.end());
}
{
auto tmp = up[v];
while (!tmp.empty()) {
res.emplace_back(tmp.top() + modUp[v]);
tmp.pop();
}
for (const int& x : res) {
cerr << x << ' ';
}
cerr << '\n';
}
}*/
void dfs(int v) {
if (g[v].empty()) {
val[v] = c[v];
slope[v] = -1;
dp[v].emplace(c[v]);
dp[v].emplace(c[v]);
return;
}
for (const int& u : g[v]) {
dfs(u);
if (dp[v].size() < dp[u].size()) {
swap(dp[v], dp[u]);
swap(val[v], val[u]);
swap(slope[v], slope[u]);
}
slope[v] += slope[u];
val[v] += val[u];
while (!dp[u].empty()) {
dp[v].emplace(dp[u].top());
dp[u].pop();
}
}
// cerr << "v: " << v + 1 << " before:\n";
// print(v);
if (par[v] != -1) {
val[v] += c[v];
while (slope[v] + (int)dp[v].size() > 1) {
dp[v].pop();
}
long long last = dp[v].top();
dp[v].pop();
long long prelast = dp[v].top();
dp[v].pop();
dp[v].emplace(prelast + c[v]);
dp[v].emplace(last + c[v]);
}
// cerr << "v: " << v + 1 << ", val: " << val[v] << ", slope: " << slope[v] << '\n';
// print(v);
}
void solve() {
int n, m;
cin >> n >> m;
par[0] = -1, c[0] = 0;
for (int i = 1; i < n + m; ++i) {
cin >> par[i] >> c[i];
--par[i];
g[par[i]].emplace_back(i);
}
dfs(0);
while (slope[0] + (int)dp[0].size() > 0) {
dp[0].pop();
}
long long ans = val[0];
vector<long long> leftPart;
while (!dp[0].empty()) {
leftPart.emplace_back(dp[0].top());
dp[0].pop();
}
leftPart.emplace_back(0);
reverse(leftPart.begin(), leftPart.end());
for (int i = 0; i < (int)leftPart.size() - 1; ++i) {
ans += (slope[0] + i) * (leftPart[i + 1] - leftPart[i]);
}
cout << ans << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int T = 1;
cin >> T;
while (T--) {
solve();
cerr << "-----------\n";
cout << "-----------\n";
}
#else
int T = 1;
// cin >> T;
while (T--) {
solve();
}
#endif
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... |