이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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(ll 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... |