제출 #1343584

#제출 시각아이디문제언어결과실행 시간메모리
1343584pcheloveksFireworks (APIO16_fireworks)C++20
100 / 100
205 ms77780 KiB
#include <bits/stdc++.h>

#define endl '\n'

//#pragma GCC optimize("Ofast")

using namespace std;

using ll = long long;
using ld = long double;
using pii = pair < int, int >;
using pll = pair < ll, ll >;

const ll INF = 2e18;
const ll DIM = 300007;
const ld PI = 3.1415926535;
const int mod = 999999893;

class convexFunction {
public:

    convexFunction() {
        k = 0;
        b = 0;
    }

    multiset < ll > x;
    ll k, b;
};

void merge(multiset < ll >& v1, multiset < ll >& v2) {
    for(auto x: v2) v1.insert(x);
}

void merge(convexFunction& f1, convexFunction& f2) {
    if(f1.x.size() < f2.x.size()) swap(f1, f2);

    f1.k += f2.k;
    f1.b += f2.b;

    merge(f1.x, f2.x);
    f2.x.clear();
}

int n, m;
vector < int > v[DIM];

ll p[DIM], c[DIM];

convexFunction f[DIM];

void dfs(int val) {
    if(v[val].size() == 0) {
        f[val].x = {c[val], c[val]};
        f[val].k = 1;
        f[val].b = -c[val];
        return;
    }

    for(auto to: v[val]) {
        dfs(to);

        merge(f[val], f[to]);
    }

    while(f[val].k > 1) {
        f[val].k--;
        f[val].b += *f[val].x.rbegin();
        f[val].x.extract(*f[val].x.rbegin());
    }

    if(val == 1) return;

    pair < ll, ll > tmp;

    tmp.first = *f[val].x.rbegin();
    f[val].x.extract(tmp.first);
    tmp.second = *f[val].x.rbegin();
    f[val].x.extract(tmp.second);

    tmp.first += c[val];
    tmp.second += c[val];

    f[val].x.insert(tmp.first);
    f[val].x.insert(tmp.second);

    f[val].b -= c[val];
}

int main() {

    cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0);

    #ifdef IloveCP
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif

    cin >> n >> m;
    for(int i = 2; i <= n + m; i++) {
        cin >> p[i] >> c[i];
        v[p[i]].push_back(i);
    }

    dfs(1);

    cout << *f[1].x.rbegin() + f[1].b << endl;


    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...