Cod sursa(job #1238917)

Utilizator diana97Diana Ghinea diana97 Data 7 octombrie 2014 22:17:11
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

ifstream f ("apm.in");
ofstream g ("apm.out");

const int NMAX = 200000 + 1;

struct Muchie {
    int a, b, cost;
    bool kept;
    Muchie (int a, int b, int cost) {
        this->a = a;
        this->b = b;
        this->cost = cost;
        this->kept = false;
    }
};

int n, m;
int sol;
int t[NMAX], r[NMAX];
vector <Muchie> muchii;

void citeste() {
    int a, b, c;
    f >> n >> m;
    for (int i = 1; i <= m; i++) {
        f >> a >> b >> c;
        muchii.push_back(Muchie(a, b, c));
    }
}

bool conditie(Muchie a, Muchie b) {
    return a.cost < b.cost;
}

int radacina(int x) {
    while (t[x] != x) x = t[x];
    return x;
}

void uneste(int x, int y) {
    t[x] = y;
}

void APM() {
    int ra, rb;
    for (int i = 0; i <= n; i++) t[i] = i, r[i] = 1;
    for (int i = 0; i < m; i++) {
        ra = radacina(muchii[i].a);
        rb = radacina(muchii[i].b);
        if (ra != rb) {
            uneste(ra, rb);
            sol += muchii[i].cost;
            muchii[i].kept = true;
        }
    }
}

void scrie() {
    g << sol << '\n' << n - 1 << '\n';
    for (int i = 0; i < m; i++)
        if (muchii[i].kept) g << muchii[i].b << ' ' << muchii[i].a << '\n';

}

int main() {
    citeste();
    sort(muchii.begin(), muchii.end(), conditie);
    APM();
    scrie();
    return 0;
}