Cod sursa(job #1541012)

Utilizator crysstyanIacob Paul Cristian crysstyan Data 3 decembrie 2015 17:33:16
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <algorithm>
#include <vector>
#define NMAX 200005

using namespace std;

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

int n, m, ans = 0, i, j, father[NMAX];
vector < pair < int, int > > sol;

struct apm
{
    int x, y, cost;
};
apm v[2 * NMAX];

bool comp(apm a, apm b)
{
    return a.cost < b.cost;
};

int get_father(int x)
{
    if (father[x] != x)
        father[x] = get_father(father[x]);
    return father[x];
}

void make_the_same(int x, int y)
{
    father[get_father(x)] = get_father(y);
}

int main()
{
    f >> n >> m;

    for (i = 1; i <= m; ++ i)
    {
        f >> v[i].x >> v[i].y >> v[i].cost;
        father[i] = i;
    }

    sort(v + 1, v + m + 1, comp);

    for (i = 1; i <= m; ++ i)
    {
        int x = v[i].x, y = v[i].y, c = v[i].cost;

        if (get_father(x) != get_father(y))
        {
            ans += c;
            make_the_same(x, y);
            sol.push_back(make_pair(x, y));
        }
    }

    g << ans << '\n' << sol.size() << '\n';

    for (auto &it : sol)
        g << it.first << " " << it.second << '\n';
    return 0;
}