Cod sursă (job #805283)

Utilizator avatar inacioata Cioata Ana Irina inacioata IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,39 kb
Rundă Arhiva de probleme Status evaluat
Dată 21 ian. 2025 11:28:08 Scor 70
#include <bits/stdc++.h>
using namespace std;


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

struct Muchie
{
    short x, y;
    int cost;
    bool operator<(const Muchie e) const
    {
        return cost < e.cost;
    }
};
Muchie a[101002];
short n, k, t[10003];
int m;

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

short 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;
}

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

int main()
{
    int i;
    Muchie e;
    fin >> n >> m >> k;
    for (i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].cost;
    sort(a + 1, a + m + 1);
    fout << Kruskal() << "\n";
    while (k--)
    {
        fin >> e.x >> e.y >> e.cost;
        for (i = m; i >= 1 && a[i].cost > e.cost; i--)
            a[i + 1] = a[i];
        a[i + 1] = e;
        m++;
        fout << Kruskal() << "\n";
    }
    return 0;
}