Cod sursa(job #2749737)

Utilizator witekIani Ispas witek Data 7 mai 2021 23:14:32
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 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 <int> h, t;
vector <pair <int, int> > apm;
int n, m, totalCost;

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


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

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

bool sameConnectedComponents(int x, int y) {
    return t[x] == t[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, cost;
    for(const auto& p : v) {
        x = p.x;
        y = p.y;
        cost = p.cost;
        if(sameConnectedComponents(x, y))
            continue;
        unite(x, y);
        totalCost += cost;
        apm.push_back({x, y});
        if(apm.size() == n - 1)
            return;
    }
}

void print() {
    g << totalCost << '\n' << n - 1 << '\n';
    for(const auto& p : apm)
        g << p.first << " " << p.second << '\n';
}

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