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 pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
int readint(){
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,m;
vector<pii> g[300005];
multiset<ll> pts[300005];
void dfs(int x,int w){
for(auto&p:g[x]) dfs(p.fi,p.se);
int ch=-1;
for(auto&p:g[x]) if(ch==-1||(int)pts[ch].size()<(int)pts[p.fi].size()) ch=p.fi;
if(ch!=-1) swap(pts[x],pts[ch]);
for(auto&p:g[x]) if(p.fi!=ch) for(ll pt:pts[p.fi]) pts[x].insert(pt);
for(int i=0;i<(int)g[x].size()-1;i++) pts[x].erase(prev(pts[x].end()));
if(w==-1) return;
if(pts[x].empty()){
pts[x].insert(w);
pts[x].insert(w);
} else {
ll a=*prev(pts[x].end());
pts[x].erase(prev(pts[x].end()));
ll b=*prev(pts[x].end());
pts[x].erase(prev(pts[x].end()));
pts[x].insert(a+w);
pts[x].insert(b+w);
}
}
int main(){
n=readint(); m=readint();
n+=m;
for(int i=2;i<=n;i++){
int p=readint(),c=readint();
g[p].pb(mp(i,c));
}
ll tot=0;
for(int i=1;i<=n;i++) for(auto&p:g[i]) tot+=p.se;
dfs(1,-1);
vector<ll> vec(1,0);
for(int pt:pts[1]) vec.pb(pt);
int c=0;
for(int i=vec.size()-1;i>0;i--){
tot+=c*(vec[i]-vec[i-1]);
c--;
}
printf("%lld\n",tot);
return 0;
}
# | 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... |