#include<bits/stdc++.h>
#define taskname "B"
using namespace std;
typedef long long ll;
template<class T>bool minimize(T& a, T b){
if(a > b){
a = b;
return true;
}
return false;
}
int n, m;
namespace sub1{
void solve(){
vector<int>a(m);
for(int& x : a){
cin >> x >> x;
}
sort(a.begin(), a.end());
int median = a[m >> 1];
ll ans = 0;
for(int& x : a){
ans += abs(x - median);
}
cout << ans;
}
}
namespace sub23{
const int lim = 5e3 + 5;
const ll INF = 1e18;
vector<pair<int, int>>g[lim];
ll ans = 0;
pair<ll, ll>dfs(int s){
if(s > n){
return make_pair(0, 0);
}
vector<pair<ll, ll>>a;
for(auto& [d, w] : g[s]){
auto [l, r] = dfs(d);
a.emplace_back(l + w, r + w);
}
vector<ll>candidate;
for(auto& [l, r] : a){
candidate.emplace_back(l);
candidate.emplace_back(r);
}
sort(candidate.begin(), candidate.end());
candidate.resize(unique(candidate.begin(), candidate.end()) - candidate.begin());
vector<ll>ret;
ll opt = INF;
for(ll& value : candidate){
ll cur = 0;
for(auto& [l, r] : a){
if(l > value || r < value){
cur += min(abs(l - value), abs(r - value));
}
}
if(minimize(opt, cur)){
ret.clear();
}
if(opt == cur){
ret.emplace_back(value);
}
}
ans += opt;
return make_pair(ret[0], ret.back());
}
void solve(){
for(int i = 2; i <= n + m; i++){
int p, c;
cin >> p >> c;
g[p].emplace_back(i, c);
}
dfs(1);
cout << ans;
}
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
if(fopen(taskname".inp", "r")){
freopen(taskname".inp", "r", stdin);
}
cin >> n >> m;
if(n == 1){
sub23::solve();
}
else if(n + m <= 5000){
sub23::solve();
}
}
Compilation message (stderr)
fireworks.cpp: In function 'int main()':
fireworks.cpp:81:24: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
81 | freopen(taskname".inp", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |