Cod sursa(job #3156240)

Utilizator lefterache_stefanLefterache Stefan lefterache_stefan Data 10 octombrie 2023 22:58:34
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <algorithm>
using namespace std;

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

const int MAXIM = 400005;

struct muchie {
    int x, y, cost;
};

pair<int, int> muchii_arbore[MAXIM];
muchie muchii[MAXIM];
int n, m, cost_total = 0, muchii_curente = 0, parinte[MAXIM];

bool comparare(muchie &a, muchie &b) {
    return a.cost < b.cost;
}

inline void citire() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> muchii[i].x >> muchii[i].y >> muchii[i].cost;
    }
}

int root(int nod) {
    while (parinte[nod] != nod) {
        nod = parinte[nod];
    }
    return nod;
}

inline void kruskal() {
    sort(muchii, muchii + m, comparare);
    for (int i = 0; i < m; i++) {
        parinte[i] = i;
    }
    for (int i = 0; i < m; i++) {
        int root1 = root(muchii[i].x);
        int root2 = root(muchii[i].y);
        if (root1 == root2) {
            continue;
        }
        parinte[root1] = root2;
        muchii_arbore[muchii_curente].first = muchii[i].x;
        muchii_arbore[muchii_curente].second = muchii[i].y;
        muchii_curente++;
        cost_total += muchii[i].cost;
    }
}

inline void afiseaza() {
    // cost total
    fout << cost_total << '\n';
    // muchii in arbore total
    fout << muchii_curente << '\n'; // n - 1
    // muchiile din arbore
    for (int i = 0; i < muchii_curente; i++) {
        fout << muchii_arbore[i].first << ' ' << muchii_arbore[i].second << '\n';
    }
}

int main() {
    citire();
    kruskal();
    afiseaza();
    return 0;
}