Cod sursa(job #1607313)

Utilizator mariapascuMaria Pascu mariapascu Data 20 februarie 2016 23:25:26
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

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

struct Edge {
    int x, y, w;
    bool operator < (const Edge& E) const {
        return w < E.w;
    }
};

int n, m;
vector<Edge> G;
vector<int> h, t;
int cost_min;
vector<Edge> arb;

void Read();
void Kruskal();
int Find(int x);
void Union(int x, int y);
void Write();

int main() {
    Read();
    Kruskal();
    Write();
    fin.close();
    fout.close();
    return 0;
}

void Kruskal() {
    sort(G.begin(), G.end());
    int k = 0;   //nr muchiilor in apm
    int c1, c2;
    for (const auto& e : G) {
        c1 = Find(e.x), c2 = Find(e.y);
        if (c1 != c2) {
            k++;
            cost_min += e.w;
            arb.push_back(e);
            Union(c1, c2);
        }
        if (k == n - 1) break;
    }
}

int Find(int x) {
    int r, y = x;
    while (y != t[y]) y = t[y];
    r = y;
    while (x != r) {
        y = t[x];
        t[x] = r;
        x = y;
    }
    return r;
}

void Union(int x, int y) {
    if (h[y] > h[x]) t[x] = y;
    else {
        t[y] = x;
        if (h[y] == h[x]) h[x]++;
    }
}

void Write() {
    fout << cost_min << '\n' << n - 1 << '\n';
    for (const auto& e : arb)
        fout << e.x << ' ' << e.y << '\n';

}

void Read() {
    fin >> n >> m;
    h = t = vector<int>(n + 1);
    for (int i = 1; i <= n; i++) t[i] = i, h[i] = 0;
    for (int i = 1, x, y, w; i <= m; i++) {
        fin >> x >> y >> w;
        G.push_back({x, y, w});
    }
}