Cod sursă (job #757144)

Utilizator avatar qpRares Bulgaru Rares qpRares IP ascuns
Problemă Zapada (clasele 11 și 12) Compilator cpp-32 | 1,68 kb
Rundă Arhiva de probleme Status evaluat
Dată 22 ian. 2024 20:58:18 Scor 40
#include <bits/stdc++.h>
using namespace std;

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

class Edge {
public:
    int x, y, cost;

    Edge(int x, int y, int cost)
        : x(x), y(y), cost(cost) {}

    bool operator<(const Edge& a) const {
        return cost < a.cost;
    }
};

vector<int> parent, Rank;

int find(int i) {
    return (parent[i] == i) ? i : (parent[i] = find(parent[i]));
}

void Union(int x, int y) {
    int x_root = find(x);
    int y_root = find(y);

    if (Rank[x_root] < Rank[y_root])
        parent[x_root] = y_root;
    else {
        parent[y_root] = x_root;
        if (Rank[x_root] == Rank[y_root])
            Rank[x_root]++;
    }
}

int kruskal(vector<Edge>& edges, int n) {
    sort(edges.begin(), edges.end());

    parent.resize(n + 1);
    Rank.resize(n + 1, 0);

    iota(parent.begin(), parent.end(), 0);

    int costMin = 0;

    for (const Edge& e : edges) {
        int x = e.x;
        int y = e.y;
        int cost = e.cost;

        if (find(x) != find(y)) {
            costMin += cost;
            Union(x, y);
        }
    }

    return costMin;
}

int main() {
    int n, m, k;
    fin >> n >> m >> k;

    vector<Edge> edges;
    edges.reserve(m + k);

    for (int i = 0; i < m; ++i) {
        int x, y, cost;
        fin >> x >> y >> cost;
        edges.emplace_back(x, y, cost);
    }

    int c0 = kruskal(edges, n);
    fout << c0 << '\n';

    for (int i = 0; i < k; ++i) {
        int x, y, cost;
        fin >> x >> y >> cost;
        edges.emplace_back(x, y, cost);
        int ck = kruskal(edges, n);
        fout << ck << '\n';
    }

    return 0;
}