Cod sursa(job #1635568)

Utilizator mariapascuMaria Pascu mariapascu Data 6 martie 2016 18:55:31
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 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, arb;
vector<int> h, t;
int cost;

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

int main() {
    Read();
    Kruskal();
    Write();

    fin.close();
    fout.close();
    return 0;
}

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

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

int Find(int x) {
    if (t[x] == x) return x;
    return t[x] = Find(t[x]);
}

void Write() {
    fout << cost << '\n' << arb.size() << '\n';
    for (const auto & e : arb) {
        fout << e.x << ' ' << e.y << '\n';
    }
}

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