Cod sursă (job #626172)

Utilizator avatar MihaiBratu Mihai-Alexandru Bratu MihaiBratu IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,44 kb
Rundă cex_gj11_12 Status evaluat
Dată 18 ian. 2022 20:11:12 Scor 50
#include <fstream>
#include <vector>
#include <map>
using namespace std;
multimap <int, pair <int, int>> pam;
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;
    multimap<int, pair<int, int>>::iterator it;
    it = pam.begin();
    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)
    {
        x = (*it).second.first;
        y = (*it).second.second;
        int rx = root(x), ry = root(y);
        if (rx != ry)
        {
            ++z;
            cost += (*it).first;
            unificare(rx, ry);
        }
        it++;
    }
    return cost;
}
int main()
{
    fin >> n >> m >> k;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;
        pam.insert(make_pair(z, make_pair(x, y)));
    }
    fout << snow() << "\n";
    for (i = 1; i <= k; i++)
    {
        fin >> x >> y >> z;
        if (1)
        {
            pam.insert(make_pair(z, make_pair(x, y)));
            fout << snow() << "\n";
        }
    }
    return 0;
}