Submission #1364229

#TimeUsernameProblemLanguageResultExecution timeMemory
13642294o2aFireworks (APIO16_fireworks)C++20
100 / 100
197 ms84892 KiB
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define _F "fireworks"
using namespace std;
typedef long long ll;

constexpr int N = 3e5 + 67;

int n, m;
ll a[N], b[N], c[N];
vector<int> C[N];
multiset<ll> S[N];

void dfs(int u)
{
    if (u > n)
    {
        S[u].insert(c[u]), S[u].insert(c[u]);
        a[u] = -1, b[u] = c[u];
        return;
    }
    int w = u;
    for (int v: C[u])
    {
        dfs(v);
        if (S[v].size() > S[w].size())
            w = v;
    }
    swap(S[u], S[w]);
    a[u] = a[w], b[u] = b[w];
    for (int v: C[u])
        if (v != w)
        {
            for (ll x: S[v])
                S[u].insert(x);
            S[v].clear();
            a[u] += a[v], b[u] += b[v];
        }
    b[u] += c[u];
    ll l, r;
    for (int i = 0; i <= C[u].size(); ++i)
    {
        if (i == C[u].size() - 1)
            l = *prev(S[u].end());
        if (i == C[u].size())
            r = *prev(S[u].end());
        S[u].erase(prev(S[u].end()));
    }
    S[u].insert(l + c[u]), S[u].insert(r + c[u]);
}

void solve()
{
    cin>>n>>m;
    for (int u = 2; u <= n+m; ++u)
    {
        int p; cin>>p>>c[u];
        C[p].pb(u);
    }
    dfs(1);
    ll cx = 0, y = b[1];
    for (ll x: S[1])
    {
        y += (x - cx)*(a[1]++);
        cx = x;
    }
    cout<<y;
}

int main()
{
    if (fopen(_F".INP", "r"))
    {
        freopen(_F".INP", "r", stdin);
        freopen(_F".OUT", "w", stdout);
    }
    else if (fopen("test.inp", "r"))
    {
        freopen("test.inp", "r", stdin);
        //freopen("test.out", "w", stdout);
    }
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int Test = 1; //cin>>Test;
    while (Test--) solve();
}

Compilation message (stderr)

fireworks.cpp: In function 'int main()':
fireworks.cpp:76:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
   76 |         freopen(_F".INP", "r", stdin);
      |         ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~
fireworks.cpp:77:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
   77 |         freopen(_F".OUT", "w", stdout);
      |         ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
fireworks.cpp:81:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
   81 |         freopen("test.inp", "r", stdin);
      |         ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...
#Result Execution timeMemoryGrader output
Fetching results...