Cod sursa(job #3235562)

Utilizator rapidu36Victor Manz rapidu36 Data 18 iunie 2024 19:53:01
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
#include <algorithm>

using namespace std;

const int N = 2e5;
const int M = 4e5;

struct muchie
{
    int x, y, c;
};

muchie e[M];
int t[N+1], nr[N+1], m, n;
bool in_apm[M];

int radacina(int x)
{
    if (t[x] == 0)
    {
        return x;
    }
    t[x] = radacina(t[x]);///compactarea drumurilor
    return t[x];
}

bool verif(int x, int y)
{
    return (radacina(x) == radacina(y));
}

void reuniune(int x, int y)
{
    int rx = radacina(x);
    int ry = radacina(y);
    if (nr[rx] < nr[ry])///multimea luix e mai mica
    {
        t[rx] = ry;
        nr[ry] += nr[rx];
    }
    else
    {
        t[ry] = rx;
        nr[rx] += nr[ry];
    }
}

bool cmp(muchie e1, muchie e2)
{
    return (e1.c < e2.c);
}

int kruskal()
{
    sort(e, e + m, cmp);
    ///initializam t si nr
    for (int i = 1; i <= n; i++)
    {
        t[i] = 0;
        nr[i] = 1;
    }
    int cost_total = 0;
    for (int i = 0; i < m; i++)
    {
        if (!verif(e[i].x, e[i].y))///extremitatile lui e[i] NU sunt deja in aceeasi multime (CC)
        {
            in_apm[i] = true;
            cost_total += e[i].c;
            reuniune(e[i].x, e[i].y);///de acum incolo aavem o singura CC
        }
    }
    return cost_total;
}

int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        in >> e[i].x >> e[i].y >> e[i].c;
    }
    out << kruskal() << "\n" << n - 1 << "\n";
    for (int i = 0; i < m; i++)
    {
        if (in_apm[i])
        {
            out << e[i].x << " " << e[i].y << "\n";
        }
    }
    in.close();
    out.close();
    return 0;
}