Cod sursă (job #676030)

Utilizator avatar cristia_razvan Cristia Razvan cristia_razvan IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,84 kb
Rundă vaslui_cls1112_15.11 Status evaluat
Dată 15 nov. 2022 20:41:08 Scor 100
#include <bits/stdc++.h>
using namespace std;

#define pb push_back

const string fn = "zapada";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

int n, m, q;

int t[12005];

vector<pair<int, pair<int, int>>> edg, best;

int Find(int x)
{
    int rx = x, y;
    while (t[rx] != 0)
        rx = t[rx];
    while (x != rx)
    {
        y = t[x];
        t[x] = rx;
        x = y;
    }
    return rx;
}
void Union(int x, int y)
{
    t[y] = x;
}

int main()
{

    ios_base::sync_with_stdio(false);
    cin.tie();

    fin >> n >> m >> q;
    while (m--)
    {
        int x, y, c;
        fin >> x >> y >> c;
        edg.pb({c, {x, y}});
    }
    sort(edg.begin(), edg.end());
    int apm = 0;
    for (unsigned int i = 0; i < edg.size(); ++i)
    {
        int x = Find(edg[i].second.first);
        int y = Find(edg[i].second.second);
        if (x != y)
        {
            Union(x, y);
            apm += edg[i].first;
            best.pb(edg[i]);
        }
    }
    fout << apm << '\n';

    while (q--)
    {
        int x, y, c;
        fin >> x >> y >> c;
        if (c > best.back().first)
            fout << apm << '\n';
        else
        {
            best.pb({c, {x, y}});
            for (unsigned int i = best.size() - 1; i >= 1 && best[i].first < best[i - 1].first; --i)
                swap(best[i], best[i - 1]);
            fill(t, t + n + 1, 0);
            apm = 0;
            for (unsigned int i = 0; i < best.size(); ++i)
            {
                int x = Find(best[i].second.first);
                int y = Find(best[i].second.second);
                if (x != y)
                {
                    Union(x, y);
                    apm += best[i].first;
                }
            }
            fout << apm << '\n';
        }
    }

    return 0;
}