Cod sursa(job #2170200)

Utilizator remus88Neatu Remus Mihai remus88 Data 14 martie 2018 22:47:09
Problema Arbore partial de cost minim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <tuple>
#define Nmax 200009
#define Emax 400009

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

typedef tuple <int, int, int> edge;

typedef pair <int,int> justedge;


int n,m,x,y,c,root[Nmax],cost,usage;
vector <justedge> sol;
vector <edge> E;

bool compare(edge a, edge b) {

    return get<2>(a) < get<2>(b);
}

int getroot(int x) {

    while (x!=root[x]) {

        x=root[x];
    }

    return x;
}

int reunion(int x, int y) {

    root[getroot(y)]=getroot(x);
}

bool check(int x, int y) {

    if (getroot(x)==getroot(y)) return 1;
    return 0;
}

void ReadInput() {

    f>>n>>m;

    for (int i=1; i<=m; ++i) {

        f>>x>>y>>c;
        E.push_back(edge(x,y,c));
    }
}

void Solve() {

    sort(E.begin(), E.end(), compare);

    for (int i=1; i<=n; ++i) root[i]=i;

    int counter=1;
    for (auto x: E)
        if (!check( get<0>(x) , get<1>(x) )) {

            ++counter;
            sol.push_back(justedge(get<0>(x) , get<1>(x)));
            cost += get<2>(x);
            ++usage;

            reunion( get<0>(x) , get<1>(x) );
        }

    g<<cost<<'\n'<<usage<<'\n';

    for (auto x: sol) g<< x.first <<' '<< x.second <<'\n';

}

int main() {

    ReadInput();
    Solve();

    f.close(); g.close();
    return 0;
}