Cod sursă (job #627164)

Utilizator avatar MihaiBratu Mihai-Alexandru Bratu MihaiBratu IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,64 kb
Rundă Arhiva de probleme Status evaluat
Dată 23 ian. 2022 13:09:14 Scor 100
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
struct muchie
{
    int x, y, c;
} v[100001];
vector <int> t, p;
ifstream fin("zapada.in");
ofstream fout("zapada.out");
int n, m, k, val, i, j, x, y, z;
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.clear(); 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);
            v[z] = v[q];
        }
        q++;
    }
    m = n - 1;
    return cost;
}
bool comp(muchie a, muchie b)
{
    return a.c < b.c;
}
void ad (muchie a)
{
    int i = m;
    while (v[i].c > a.c)
    {
        v[i+1] = v[i];
        i--;
    }
    v[i+1] = a;
}
int main()
{
    fin >> n >> m >> k; 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 + 1, v + m + 1, comp);
    val = snow();
    fout << val << "\n";
    for (i = 1; i <= k; i++)
    {
        muchie a;
        fin >> a.x >> a.y >> a.c;
        if (a.c > v[m].c)
        {
            fout << val << "\n";
            continue;
        }
        ad(a);
        val = snow();
        fout << val << "\n";
    }
    return 0;
}