Cod sursa(job #897751)

Utilizator andreea29Iorga Andreea andreea29 Data 27 februarie 2013 22:01:03
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include<fstream>
#include<algorithm>
#include<vector>

#define Nmax 400100

using namespace std;

int a, b, i, n, m, x[Nmax], y[Nmax], t[Nmax], cost[Nmax], par[Nmax], sol;
vector <int> solutie;

int find(int r)
{
    if (par[r] == r)
        return r;

    par[r] = find(par[r]);

    return par[r];
}

void unite(int a, int b)
{
    par[find(a)] = find(b);
}

bool cmp (int i, int j)
{
    return (cost[i] < cost[j]);
}

int main()
{
    ifstream f("apm.in");
    ofstream h("apm.out");
    f >> n >> m;
    for (i = 1; i <= m; ++i)
    {
        f >> x[i] >> y[i] >> cost[i];
        t[i] = i;
    }
    sort (t + 1, t + m + 1, cmp);
    for (i = 1; i <= n; ++i)
        par[i] = i;
    for (i = 1; i <= m; ++i)
        if (find(x[t[i]]) != find(y[t[i]]))
        {
            sol += cost[t[i]];
            unite (x[t[i]], y[t[i]]);
            solutie.push_back(t[i]);
        }
    h << sol << '\n' << n - 1 << '\n';
    for (i = 0; i < n - 1; ++i)
        h << x[solutie[i]] << " " << y[solutie[i]] << '\n';
    f.close();
    h.close();
    return 0;
}