Cod sursă (job #626123)

Utilizator avatar MihaiBratu Mihai-Alexandru Bratu MihaiBratu IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,50 kb
Rundă cex_gj11_12 Status evaluat
Dată 18 ian. 2022 18:43:17 Scor 40
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct muchie
{
    int x, y, c;
};
vector <muchie> v;
ifstream fin("zapada.in");
ofstream fout("zapada.out");
int n, m, k, i, j, x, y, z;
vector <int> viz;
vector <int> t, p;
int root(int b)
{
    while (b != t[b])
        b = t[b];
    return b;
}
void unificare(int x, int y)
{
    if (p[x] < p[y])
        t[x] = y;
    if (p[x] > p[y])
        t[y] = x;
    if (p[x] == p[y])
    {
        t[y] = x;
        p[x]++;
    }
}
int snow()
{
    int q = 1; z = 0;
    int cost = 0;
    t.resize(n + 1); p.resize(1); p.resize(n + 1);
    for (int i = 1; i <= n; i++)
        t[i] = i;
    while (z < n - 1)
    {
        int rx = root(v[q].x), ry = root(v[q].y);
        if (rx != ry)
        {
            ++z;
            cost += v[q].c;
            unificare(rx, ry);
        }
        q++;
    }
    return cost;
}
bool comp(muchie a, muchie b)
{
    return a.c < b.c;
}
int main()
{
    fin >> n >> m >> k; v.resize(m + 1); t.resize(n + 1); p.resize(n + 1);
    for (i = 1; i <= m; i++)
        fin >> v[i].x >> v[i].y >> v[i].c;
    sort(v.begin() + 1, v.end(), comp);
    fout << snow() << "\n";
    for (i = 1; i <= k; i++)
    {
        m++;
        fin >> x >> y >> z;
        muchie a;
        a.x = x; a.y = y; a.c = z;
        v.push_back(a);
        p.resize(m + 1);
        sort(v.begin() + 1, v.end(), comp);
        fout << snow() << "\n";
    }
    return 0;
}