Cod sursă (job #804454)

Utilizator avatar inacioata Cioata Ana Irina inacioata IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1.37 kb
Rundă Arhiva de probleme Status evaluat
Dată 15 ian. 2025 09:06:14 Scor 40
#include <bits/stdc++.h>
using namespace std;
ifstream fin("zapada.in");
ofstream fout("zapada.out");

struct muchie
{
    short x, y, c;
    bool operator< (muchie m) const
    {
        return c < m.c;
    }
};

muchie a[10001];
short n, m, p, t[10001], nrm;
int costTotal;

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

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

void Citire()
{
    fin >> n >> m >> p; nrm = m;
    for(short i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].c;
}

void Kruskal()
{
    int i, nrc = n, x, y;
    sort(a + 1, a + m + 1);
    for(i = 1; i <= m && nrc > 1; i++)
    {
        x = Find(a[i].x);
        y = Find(a[i].y);
        if (x != y)
        {
            Union(x, y);
            nrc--;
            costTotal += a[i].c;
        }
    }
}
void Reset()
{
    for(short i = 1; i <= n; i++)
        t[i] = 0;
}

void Add()
{
    for(short i = nrm + 1; i <= nrm + p; i++)
    {
        fin >> a[i].x >> a[i].y >> a[i].c;
        m++; costTotal = 0; Reset();
        Kruskal();
        fout << costTotal << "\n";
    }
}

int main()
{
    Citire();
    Kruskal();
    fout << costTotal << "\n";
    Add();
    return 0;
}