제출 #1249103

#제출 시각아이디문제언어결과실행 시간메모리
1249103Chris_BlackFireworks (APIO16_fireworks)C++20
100 / 100
192 ms109128 KiB
//#pragma GCC optimize("Ofast")
//#pragma GCC target("avx2")

#include <bits/stdc++.h>

#define ll long long
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define FORR(i, a, b) for(int i = a; i >= b; --i)
#define pii pair<int, int>
#define ff first
#define ss second
#define pll pair<ll, ll>
#define vpi vector<pii>
#define vvpi vector<vpi>
#define vpl vector<pll>
#define vvpl vector<vpl>
#define vl vector<ll>
#define vvl vector<vl>
//#define x first
//#define y second


using namespace std;
const int N = 1e6 + 9, LGV = 33, LGN = 21, Mod = 1e9 + 7;
//const int Inf = 0x3f3f3f3f;
const ll Inf = LLONG_MAX / 2;
const bool test_case = false;

//ifstream fin("landscape.in");
//ofstream fout("landscape.out");
//#define cin fin
//#define cout fout

int n, m, t[N], cst[N];

priority_queue<ll> q[N];

vvi G(N);

void Dfs(int x = 1, int p = 0)
{
    if(G[x].size() == 0 && x != 1)
    {
        q[x].push(cst[x]);
        q[x].push(cst[x]);
        return;
    }

    for(auto y : G[x])
    {
        Dfs(y, x);

        if(q[x].size() < q[y].size())
            swap(q[x], q[y]);

        while(!q[y].empty())
        {
            q[x].push(q[y].top());
            q[y].pop();
        }
    }

    for(int i = 1; i < G[x].size(); ++i)
        q[x].pop();

    ll v1 = q[x].top(); q[x].pop();
    ll v2 = q[x].top();

    ///This line has double responsibility,
    ///the second element should also be removed to
    ///simulate adding cst[x] to the elements on the
    ///left side of the slopes
    ///but at the same time contribute to the total slope
    q[x].pop();


    q[x].push(v1 + cst[x]);
    q[x].push(v2 + cst[x]);
}

void solve()
{
    cin >> n >> m;

    int p, c;
    FOR(i, 2, n + m)
    {
        cin >> p >> c;
        t[i] = p; cst[i] = c;
        G[p].pb(i);
    }

    Dfs(1, 0);

    ll ans = 0;
    FOR(i, 1, n + m)ans += cst[i];

    q[1].pop();
    while(!q[1].empty())
    {
        ans -= q[1].top();
        q[1].pop();
    }

    cout << ans << '\n';
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    int t = 1;
    if(test_case)cin >> t;
    while(t --)solve();
    return 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...