Cod sursa(job #949173)

Utilizator BitOneSAlexandru BitOne Data 12 mai 2013 18:43:25
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <tuple>
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

const int NMAX = 200011;
typedef tuple<int, int, int> pr;

int r[NMAX], f[NMAX];
vector<pr> G, apm;


namespace std
{
    inline istream& operator>>(istream& in, pr& x)
    {
        in >> get<0>(x) >> get<1>(x) >> get<2>(x);
        return in;
    }
    inline ostream& operator<<(ostream& out, const pr& x)
    {
        out << get<0>(x) << ' ' << get<1>(x);
        return out;
    }
}

int find(int x)
{
    int y, z;
    for(y = f[x]; y != f[y]; y = f[y]);
    while(x != f[x])
    {
        z = f[x];
        f[x] = y;
        x = z;
    }
    return y;
}
void Union(int x, int y)
{
    int fx = find(x), fy = find(y);

    if(fx == fy) return;
    if(r[fx] < r[fy]) f[fx] = fy;
    else if(r[fy] > r[fx]) f[fy] = fx;
    else {
            f[fx] = fy;
            ++r[fy];
         }
}

int main()
{
    int N, M, fx, fy, cost;
    ifstream in("apm.in");
    ofstream out("apm.out");

    in >> N >> M;
    copy(istream_iterator<pr>(in), istream_iterator<pr>(), back_inserter(G));

    cost = 0;
    for(int i = 1; i <= N; ++i)
    {
        f[i] = i;
        r[i] = 1;
    }
    sort(G.begin(), G.end(), [](const pr& x, const pr& y) {return get<2>(x) < get<2>(y);});
    for(auto& x : G)
    {
        fx = find(get<0>(x));
        fy = find(get<1>(x));
        if(fx == fy) continue;
        cost += get<2>(x);
        Union(fx, fy);
        apm.push_back(move(x));
        if(N - 1 == apm.size()) break;
    }
    out << cost << '\n' << apm.size() << '\n';
    copy(apm.begin(), apm.end(), ostream_iterator<pr>(out, "\n"));

    return EXIT_SUCCESS;
}