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 int int64_t
#define pb push_back
using pii=pair<int,int>;
const int lim=2e5+100;
const int mod=1e9+7;
#ifndef Local
#define pd(x) ;
#else
void pd(priority_queue<int>pq){
while(pq.size()){
cerr<<pq.top()<<' ';
pq.pop();
}
cerr<<'\n';
}
#endif
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#ifdef Local
freopen(".in","r",stdin);freopen(".out","w",stdout);
#endif
int n,m;
cin>>n>>m;
int N=n+m;
int d[N]{};
vector<int>v[N];
for(int i=1;i<N;i++){
int p;
cin>>p>>d[i];
p--;
v[p].pb(i);
}
priority_queue<int>l[N];
priority_queue<int,vector<int>,greater<int>>r[N];
for(int i=N-1;n<=i;i--){
l[i].push(d[i]);
r[i].push(d[i]);
}
int ans=0;
for(int i=n-1;0<=i;i--){
for(int j:v[i]){
if(!l[i].size()){
l[i].swap(l[j]);
r[i].swap(r[j]);
continue;
}
if(l[i].size()<l[j].size()){
l[i].swap(l[j]);
r[i].swap(r[j]);
}
while(l[j].size()){
int lt=l[j].top(),rt=r[j].top();
l[j].pop(),r[j].pop();
if(rt<l[i].top()){
ans+=l[i].top()-rt;
r[i].push(l[i].top());
l[i].pop();
l[i].push(lt);
l[i].push(rt);
}else if(r[i].top()<lt){
ans+=lt-r[i].top();
l[i].push(r[i].top());
r[i].pop();
r[i].push(lt);
r[i].push(rt);
}else{
l[i].push(lt);
r[i].push(rt);
}
}
}
int k=r[i].top();
while(r[i].size()&&r[i].top()!=INT_MAX){
r[i].pop();
}
l[i].push(l[i].top()+d[i]);
r[i].push(k+d[i]);
while(r[i].size()<l[i].size())r[i].push(INT_MAX);
}
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... |