제출 #1175953

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

using namespace std;

#define int long long

int inf = 1e13;

int n, m;
int t[300005], c[300005];
vector<int> f[300005];

struct schema_pantei
{
    int a = 0, b = 0;///cum arata la final
    priority_queue<int> pq;///punctele unde se schimba
};

schema_pantei s[300005];
int cine[300005];

void join(int x, int y)
{
    while (x != cine[x])
        x = cine[x];
    while (y != cine[y])
        y = cine[y];
    if (s[x].pq.size() < s[y].pq.size())
    {
        while (!s[x].pq.empty())
            s[y].pq.push(s[x].pq.top()), s[x].pq.pop();
        s[y].a += s[x].a;
        s[y].b += s[x].b;
        cine[x] = y;
    }
    else
    {
        while (!s[y].pq.empty())
            s[x].pq.push(s[y].pq.top()), s[y].pq.pop();
        s[x].a += s[y].a;
        s[x].b += s[y].b;
    }
}

void dfs(int nod)
{
    if (f[nod].empty())
    {
        cine[nod] = nod;
        s[nod].a = 1;
        s[nod].b = -c[nod];
        s[nod].pq.push(c[nod]);
        s[nod].pq.push(c[nod]);
    }
    else
    {
        for (auto fiu : f[nod])
            dfs(fiu);
        cine[nod] = nod;
        for (auto fiu : f[nod])
            join(nod, fiu);
        int nd = nod;///!!!
        while (cine[nd] != nd)
            nd = cine[nd];
        while (s[nd].a > 1)
        {
            s[nd].b += s[nd].pq.top();
            s[nd].pq.pop();
            s[nd].a--;
        }
        if (s[nd].a != 1)
            assert(false);
        int sl1 = s[nd].pq.top();
        s[nd].pq.pop();
        int sl0 = s[nd].pq.top();
        s[nd].pq.pop();
        s[nd].pq.push(sl0 + c[nod]);
        s[nd].pq.push(sl1 + c[nod]);
        s[nd].b -= c[nod];
    }
}

signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin >> n >> m;
    n += m;
    for (int i = 2; i <= n; i++)
    {
        cin >> t[i] >> c[i];
        f[t[i]].push_back(i);
    }
    dfs(1);
    int nd = 1;
    while (nd != cine[nd])
        nd = cine[nd];
    cout << s[nd].b + s[nd].pq.top();
    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...