Cod sursa(job #2353297)

Utilizator tigeraOprea Tereza Emilia tigera Data 24 februarie 2019 10:04:30
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

ifstream fin ("apm.in");
ofstream fout ("apm.out");

struct muchie {
    int x, y, c;
} mu[400010], apm[200010];

int comp (muchie a, muchie b)
{
    if (a.c < b.c)
        return 1;
    else
        return 0;
}

int n, m, nr_muchii, ct;
int p[200010], h[200010], a, b;

int gaseste_parinte (int k)
{
    while (p[k] != k)
        k = p[k];
    return p[k];
}

int main() {
    fin >> n >> m;
    for (int i=1; i<=m; i++)
        fin >> mu[i].x >> mu[i].y >> mu[i].c;
    sort (mu+1, mu+m+1, comp);
    for (int i=1; i<=n; i++)
    {
        p[i] = i;
        h[i] = 1;
    }
    for (int i=1; i<=m && nr_muchii < n-1; i++)
    {
        a = gaseste_parinte(mu[i].x);
        b = gaseste_parinte(mu[i].y);
        if (a == b)
            continue;
        ct += mu[i].c;
        apm[++nr_muchii] = mu[i];
        if (h[a] == h[b])
        {
            h[a]++;
            p[b] = a;
        }
        else if (h[a] < h[b])
            p[a] = b;
        else
            p[b] = a;
    }
    fout << ct << '\n';
    fout << nr_muchii << '\n';
    for (int i=1; i<=nr_muchii; i++)
        fout << apm[i].x << ' ' << apm[i].y << '\n';
     return 0;
}