This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//Challenge: Accepted
#include <bits/stdc++.h>
using namespace std;
#ifdef zisk
void debug(){cout << endl;}
template<class T,class ... U> void debug(T a, U ... b){cout << a << " ", debug(b...);}
template<class T> void pary(T l, T r) {
while (l != r) cout << *l << " ", l++;
cout << endl;
}
#else
#define debug(...) 0
#define pary(...) 0
#endif
#define ll long long
#define maxn 300005
#define pii pair<ll, ll>
#define ff first
#define ss second
#define io ios_base::sync_with_stdio(0);cin.tie(0);
#define se multiset<ll>
vector<pii> adj[maxn];
void merge(se &a, se &b) {
if (b.size() > a.size()) swap(a, b);
for (auto i:b) a.insert(i);
b.clear();
}
ll vy[maxn]; //cost at 0
se dfs(int n) {
se ret;
int chi = 0;
for (auto [v, e]:adj[n]) {
chi++;
se tmp = dfs(v);
ll pr = *prev(tmp.end());
tmp.erase(prev(tmp.end()));
ll pl = *prev(tmp.end());
tmp.erase(prev(tmp.end()));
tmp.insert(pl + e), tmp.insert(pr + e);
vy[n] += vy[v] + e;
merge(ret, tmp);
}
for (int i = 0;i < chi - 1;i++) {
ret.erase(prev(ret.end()));
}
if (chi == 0) {
ret.insert(0);
ret.insert(0);
}
return ret;
}
int main() {
io
int n, m;
cin >> n >> m;
for (int i = 2;i <= n + m;i++) {
int pi, ci;
cin >> pi >> ci;
adj[pi].push_back({i, ci});
}
se s = dfs(1);
ll ans = vy[1], slope = -s.size() + 1, curx = 0;
for (auto i:s) {
ans += slope * (i - curx);
curx = i;
slope++;
}
cout << ans << "\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... |