Submission #1091875

#TimeUsernameProblemLanguageResultExecution timeMemory
1091875ASN49KFireworks (APIO16_fireworks)C++14
7 / 100
5 ms7516 KiB
#include <bits/stdc++.h>
using namespace std;
using i64=long long;
#define UNUSED -1
#define all(x) x.begin(),x.end()
#define pb push_back
const int mod=1e9+7,inf=1e9+1;
const int N=3e5;
vector<pair<int,int>>g[N];
i64 best[N][2];
i64 rez[N];
void dfs(int nod)
{
    if(g[nod].size()==0)
    {
        return;
    }

    multiset<i64>mp;
    for(auto &c:g[nod])
    {
        dfs(c.first);
        best[c.first][0]+=c.second;
        best[c.first][1]+=c.second;
        mp.insert(best[c.first][0]);
        mp.insert(best[c.first][1]);
    }
    while(mp.size()>2)
    {
        mp.erase(mp.find(*mp.begin()));
        mp.erase(mp.find(*mp.rbegin()));
    }

    best[nod][0]=*mp.begin();
    best[nod][1]=*mp.rbegin();

    i64 x=best[nod][0];
    for(auto &c:g[nod])
    {
        rez[nod]+=rez[c.first];
        rez[nod]+=max(x-best[c.first][1] , 0LL);
        rez[nod]+=max(best[c.first][0]-x , 0LL);
    }

}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,m;
    cin>>n>>m;
    n+=m;
    for(int i=1;i<n;i++)
    {
        int x,y;
        cin>>x>>y;
        x--;
        g[x].pb({i,y});
    }
    dfs(0);
    cout<<rez[0];
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...