Cod sursa(job #2716981)

Utilizator witekIani Ispas witek Data 6 martie 2021 01:00:01
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

struct edge {
    int x, y, cost;

    bool operator <(const edge& other) const {
        return cost < other.cost;
    }
};

int n, m, totalCost;
vector <edge> v, apm;
vector <int> t, h;

void init() {
    t = vector <int> (n + 1);
    h = vector <int> (n + 1, 1);
    for(int i = 1; i <= n; ++i)
        t[i] = i;
}

int getRoot(int node) {
    if(node == t[node])
        return node;
    return (t[node] = getRoot(t[node]));
}

bool sameConnectedComponents(int x, int y) {
    return getRoot(x) == getRoot(y);
}

void unite(int x, int y) {
    int rootX = getRoot(x);
    int rootY = getRoot(y);
    if(sameConnectedComponents(x, y))
        return;
    if(h[rootX] < h[rootY]) {
        t[rootX] = rootY;
    }
    else {
        if(h[rootX] == h[rootY])
            ++h[rootX];
        t[rootY] = rootX;
    }
}

void read() {
    f >> n >> m;
    init();
    int x, y, c;
    for(int i = 1; i <= m; ++i) {
        f >> x >> y >> c;
        v.push_back({x, y, c});
    }
    sort(v.begin(), v.end());
}

void kruskal() {
    int x, y, c;
    for(const auto& muchie : v) {
        x = muchie.x;
        y = muchie.y;
        c = muchie.cost;
        if(sameConnectedComponents(x, y))
            continue;
        unite(x, y);
        totalCost += c;
        apm.push_back({x, y, c});
        if(apm.size() == n - 1)
            break;
    }
}

int main()
{
    read();
    kruskal();
    g << totalCost << '\n' << n - 1 << "\n";
    for(const auto& p : apm)
        g << p.x << " " << p.y << '\n';
    return 0;
}