Cod sursă (job #676018)

Utilizator avatar Latyn76 Tinica Alexandru Stefan Latyn76 IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 2,38 kb
Rundă vaslui_cls1112_15.11 Status evaluat
Dată 15 nov. 2022 20:23:06 Scor 80
//in the name of God
//PLZ DA MI MACAR EXEMPLUL
#include <bits/stdc++.h>
using namespace std;
ifstream fin("zapada.in");
ofstream fout("zapada.out");

const int NMAX = 10007;
int n, m, k, c, cost;
int t[NMAX], rad[NMAX], viz[NMAX];
struct vrajeala
{
    int a, b, cost;
};
vector <vrajeala> nod, nou;

bool cmp(vrajeala a, vrajeala b)
{
    return a.cost < b.cost;
}

void Union(int x, int y)
{
    t[y] = x;
}

int Find(int x)
{
    int y, rad = x;
    while (t[rad] != rad)
        rad = t[rad];
    ///comprimare
    while (x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

int main()
{
    fin >> n >> m >> k;
    int x, y;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        nod.push_back({ x,y,c });
    }
    sort(nod.begin(), nod.end(), cmp);
    for (int i = 1; i <= n; i++)
        t[i] = i;
    for (int i = 0; i < m; i++)
    {
        x = Find(nod[i].a);
        y = Find(nod[i].b);
        if (x != y)
        {
            Union(x, y);
            nou.push_back(nod[i]);
            cost += nod[i].cost;
        }
        ///cout << 8;
    }
    fout << cost << '\n';
    while (k--)
    {
        fin >> x >> y >> c;
        if (c < nou[nou.size() - 1].cost) /// nu are rost sa caut daca e deja mai mare si drumul era posibil
        {
            nou.push_back({ x,y,c });
            /// poate un pas e mai bun decat n log n lol
            for (int i = nou.size() - 1; i > 0; i--)
            {
                if (nou[i].cost < nou[i - 1].cost)
                    swap(nou[i], nou[i - 1]);
                else break;
            }
            /// copy pasta de la inceput
            /// dar dau si reset
            nod = nou;
            nou.clear();
            cost = 0;
            for (int i = 1; i <= n; i++)
            {
                t[i] = i;
                rad[i] = 0;
            }
            for (int i = 0; i < n; i++)
            {
                x = Find(nod[i].a);
                y = Find(nod[i].b);
                if (x != y)
                {
                    Union(x, y);
                    nou.push_back(nod[i]);
                    cost += nod[i].cost;
                }
            }
            fout << cost << '\n';
        }
        else fout << cost << '\n'; /// ramamee neschimbat
    }
    return 0;
}