Cod sursa(job #3156349)

Utilizator lefterache_stefanLefterache Stefan lefterache_stefan Data 11 octombrie 2023 11:47:15
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

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

const int MAXIM = 400005;

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

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

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

inline void citire() {
    fin >> n >> m;
    muchii.resize(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 uneste(int nod1, int nod2) {
    if (rang[nod1] < rang[nod2]) {
        parinte[nod1] = nod2;
    } else if (rang[nod1] > rang[nod2]) {
        parinte[nod2] = nod1;
    } else {
        parinte[nod1] = nod2;
        rang[nod2]++;
    }
}

inline void kruskal() {
    muchii_arbore.reserve(n);
    sort(muchii.begin(), muchii.end(), 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;
        }
        uneste(root1, root2);
        muchii_arbore.push_back(make_pair(muchii[i].x, muchii[i].y));
        cost_total += muchii[i].cost;
    }
}

inline void afiseaza() {
    // cost total
    fout << cost_total << '\n';
    // muchii in arbore total
    fout << n - 1 << '\n';
    // muchiile din arbore
    for (auto x : muchii_arbore) {
        fout << x.first << ' ' << x.second << '\n';
    }
}

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