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>
#define pii pair<int, int>
#define ll long long
using namespace std;
const int MAXN = 3e5;
vector<pii> edges[MAXN]; // node, cost
int parent[MAXN];
int lval[MAXN]; // inclusive
int rval[MAXN]; // inclusive
ll cost[MAXN];
int n;
void dfs(int s = 0) {
int m = edges[s].size();
if (m == 0) {
cost[s] = 0;
lval[s] = 0;
rval[s] = 0;
return;
}
for (pii e: edges[s]) {
dfs(e.first);
}
vector<int> change_pos;
ll at0 = 0;
for (pii e: edges[s]) {
change_pos.push_back(e.second+lval[e.first]);
change_pos.push_back(e.second+rval[e.first]);
at0 += lval[e.first]+cost[e.first]+e.second;
}
sort(change_pos.begin(), change_pos.end());
for (int i = 0; i < m; i++) {
at0 -= change_pos[i];
}
cost[s] = at0;
lval[s] = change_pos[m-1];
rval[s] = change_pos[m];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int a, b; cin >> a >> b; n = a+b;
for (int i = 0; i < n-1; i++) {
int x, c;
cin >> x >> c;
parent[i+1] = x-1;
edges[x-1].push_back(pii(i+1, c));
}
dfs();
cout << cost[0] << "\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... |