Cod sursa(job #1204344)

Utilizator florin.elfusFlorin Elfus florin.elfus Data 2 iulie 2014 18:05:42
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

const int nmax = 200000;

int n, m;
int cost, nrmuchii;
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 v[nmax + 1];
vector <Muchie> muchii;

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

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

int father(int node) {
    return v[node] = (v[node] == node ? node : father(v[node]));
}

void APM () {
    for (int i = 0; i < m; i++) {
        if (v[muchii[i].a] != v[muchii[i].b]) {
            nrmuchii++;
            cost += muchii[i].cost;
            muchii[i].kept = true;
            v[father(muchii[i].a)] = father(v[muchii[i].b]);
        }
    }
}

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

int main () {
    citeste ();

    for (int i = 1; i <= n; i++) v[i] = i;
    sort (muchii.begin (), muchii.end (), conditie());

    APM ();

    scrie ();

    return 0;
}