Cod sursă (job #675973)

Utilizator avatar tomaionut IDorando tomaionut IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 2,31 kb
Rundă vaslui_cls1112_15.11 Status evaluat
Dată 15 nov. 2022 19:39:36 Scor 70
#include <bits/stdc++.h>

using namespace std;

ifstream fin("zapada.in");
ofstream fout("zapada.out");

struct vrajeala
{
    int x, y, c;
    bool operator < (const vrajeala A) const
    {
        return c < A.c;
    }
}a[200005];

struct DSU
{
    vector <int> t;
    vector <int> nr;
    DSU(int n)
    {
        t.resize(n + 5);      
    }

    void Init(int n)
    {
        nr.resize(n + 5);
        for (int i = 1; i <= n; i++)
            nr[i] = 1;
    }

    void Union(int x, int y)
    {
        /// +10p ?
        if (nr[x] < nr[y])
            t[x] = y;
        else
        {
            t[y] = x;
            if (nr[x] == nr[y])
                nr[x]++;
        }
    }

    int Find(int x)
    {
        int r = x, y;
        while (t[r])
            r = t[r];

        while (x != r)
        {
            y = t[x];
            t[x] = r;
            x = y;
        }

        return r;
    }
};
int n, m, q;
void Test_Case()
{
    int i, nrcc, x, y, apm = 0;
    fin >> n >> m >> q;
    nrcc = n;
    DSU tree(n);
    tree.Init(n);
    for (i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].c;
    sort(a + 1, a + m + 1);
    for (i = 1; i <= m and nrcc > 1; i++)
    {
        x = tree.Find(a[i].x);
        y = tree.Find(a[i].y);
        if (x != y)
        {
            tree.Union(x, y);
            nrcc--;
            apm += a[i].c;
        }
    }
    fout << apm << "\n";
    while (q--)
    {
        m++;
        fin >> a[m].x >> a[m].y >> a[m].c;
        if (a[m].c > a[m - 1].c)
        {
            m--;
            fout << apm << "\n";
            continue;
        }
        for (i = m; i >= 1 and a[i].c < a[i - 1].c; i--)
            swap(a[i], a[i - 1]);
        DSU tree(n);
        tree.Init(n);
        apm = 0;
        nrcc = n;
        for (i = 1; i <= m and nrcc > 1; i++)
        {
            x = tree.Find(a[i].x);
            y = tree.Find(a[i].y);
            if (x != y)
            {
                tree.Union(x, y);
                nrcc--;
                apm += a[i].c;
            }
        }
        fout << apm << "\n";

    }
}

int main()
{
    int t;
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    t = 1;
    while (t--)
        Test_Case();

    return 0;
}