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;
#define f first
#define s second
typedef long long ll;
const int maxn = 3e5+5;
const ll inf = 1e18;
ll ans = 0;
int n, m;
int w[maxn];
vector<int> tree[maxn];
pair<ll, int> dfs(int x){
if(x > n)return {w[x], w[x]};
vector<pair<ll, int>> op;
for(auto v: tree[x]){
auto tmp = dfs(v);
op.push_back({tmp.f, 0});
op.push_back({tmp.s, 1});
}
sort(op.begin(), op.end());
ll mid = op[op.size()/2].f;
for(auto v: op){
if(v.s)ans += max(0LL, mid - v.f);
else ans += max(0LL, v.f-mid);
}
return {op[op.size()/2-1].f+w[x], op[op.size()/2].f+w[x]};
}
int main(){
cin >> n >> m;
for(int i = 2; i <= n+m; i++){
int x;
cin >> x >> w[i];
tree[x].push_back(i);
}
dfs(1);
cout << ans;
}
# | 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... |