Cod sursa(job #2791046)

Utilizator witekIani Ispas witek Data 30 octombrie 2021 00:09:59
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 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;
    }
};

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


void init() {
    v = vector <edge> (n + 1);
    h = vector <int> (n + 1);
    t = vector <int> (n + 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(rootX == rootY)
        return;
    if(h[rootX] < h[rootY])
        t[rootX] = rootY;
    else {
        if(h[rootX] == h[rootY])
            ++h[rootX];
        t[rootY] = rootX;
    }
}

void kruskal() {
    int x, y, c;
    for(const auto& p : v) {
        x = p.x;
        y = p.y;
        c = p.cost;
        if(sameConnectedComponents(x, y))
            continue;
        unite(x, y);
        sum += c;
        apm.push_back({x, y});
    }
}

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 print() {
    g << sum << '\n' << apm.size() << '\n';
    for(const auto& i : apm)
        g << i.first << " " << i.second << '\n';
}

int main()
{
    read();
    kruskal();
    print();
}