Cod sursă (job #624892)

Utilizator avatar robertanechita1 Roberta Nechita robertanechita1 IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,30 kb
Rundă Arhiva de probleme Status evaluat
Dată 12 ian. 2022 18:52:01 Scor 70
#include <bits/stdc++.h>

using namespace std;

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

int nrc, n, m, k, t[10005], cMin;

struct muchie
{
    int x, y, c;
    bool operator < (const muchie A) const
    {
        return c < A.c;
    }
};
muchie h[110005];

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

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

void Kruskal(int w)
{
    nrc = n;
    cMin = 0;
    for(int i = 1; i <= n; i++)
        t[i] = 0;
    for(int i = 1; i <= w && nrc > 1; i++)
    {
        int x = Find(h[i].x);
        int y = Find(h[i].y);
        if(x != y)
        {
            nrc--;
            Union(x, y);
            cMin += h[i].c;
        }
    }
    fout << cMin << "\n";
}

int main()
{
    fin >> n >> m >> k;
    for(int i = 1; i <= m; i++)
        fin >> h[i].x >> h[i].y >> h[i].c;
    sort(h + 1, h + m + 1);
    Kruskal(m);
    for(int i = 1; i <= k; i++)
    {
        m++;
        fin >> h[m].x >> h[m].y >> h[m].c;
        for(int j = m - 1; j > 0 && h[j + 1].c < h[j].c; j--)
            swap(h[j+1], h[j]);
        Kruskal(m);
    }
    return 0;
}