Cod sursa(job #2169159)

Utilizator andreimuthMuth Andrei andreimuth Data 14 martie 2018 13:44:32
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#define nmax 200001
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin ("apm.in");
ofstream fout ("apm.out");

pair < int, pair < int, int > > mu[nmax];
//struct cel {int first, second;}; cel sol[nmax];
int i, j, c, tata[nmax], cm, n, m, x, y, fx, fy, nr;
vector < pair <int, int> > sol;

int f (int x)
{
    if (tata[x] == x)
        return x;
    return tata[x] = f(tata[x]);
}

int main()
{
    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {   fin >> x >> y >> c;
        mu[i] = make_pair (c, make_pair (x, y));
    }
    sort (mu + 1, mu + 1 + m);
    for (i = 1; i <= n; i++)
        tata[i] = i;

    for (i = 1; i <= m; i++)
    {
        x = mu[i].second.first;
        y = mu[i].second.second;
        fx = f (x);
        fy = f (y);
        if (fx != fy)
        {
            sol.push_back (make_pair (x, y));
            if (fx > fy)
            {
                tata[fx] = fy;
            }
            else
                tata[fy] = fx;

            cm += mu[i].first;
        }
    }

    fout << cm << "\n" << sol.size () << "\n";
    for (int i = 0; i < sol.size (); i++)
        fout << sol[i].first << " " << sol[i].second << "\n";

    return 0;
}