Cod sursa(job #2648391)

Utilizator popoviciAna16Popovici Ana popoviciAna16 Data 10 septembrie 2020 16:55:01
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <algorithm>
using namespace std;

//I. KRUSKAL

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

struct much
{
    int a, b, c;
} v[400001];
bool ok[400001];

int h[200001], t[200001];

void comb(int x, int y)
{
    if (h[x] < h[y])
        t[x] = y;
    else
    {
        t[y] = x;
        if (h[x] == h[y])
            h[x]++;
    }
}

int find(int x) //returneaza reprezentantul lui x
{
    int r, y, y2;
    r = x;
    while (t[r] != 0)
        r = t[r];
    y = x;
    while (y != r)
    {
        y2 = t[y];
        t[y] = r;
        y = y2;
    }
    return r;
}

int main()
{
    int n, m, i, x, y;
    int nrmuch = 0;
    int cost = 0;
    fin >> n >> m;
    for (i = 1; i<=m; i++)
        fin >> v[i].a >> v[i].b >> v[i].c;
    sort(v+1, v+m+1, [](much a, much b) {return a.c < b.c;});
    for (i = 1; nrmuch < n-1; i++)
    {
        x = v[i].a;
        y = v[i].b;
        if (find(x) != find(y))
        {
            ok[i] = 1;
            cost += v[i].c;
            nrmuch++;
            comb(x, y);
        }
    }
    fout << cost << '\n' << n-1 << '\n';
    for (i = 1; i<=m; i++)
        if (ok[i])
            fout << v[i].a << ' ' << v[i].b << '\n';
    return 0;
}