Cod sursa(job #2979768)

Utilizator Elvis_CostinTuca Elvis-Costin Elvis_Costin Data 15 februarie 2023 20:51:55
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>
using namespace std;
string np = "text";
ifstream f(np + ".in");
ofstream g(np + ".out");

// #define f cin
// #define g cout

int n, m, ctotal, rez;
struct muchie
{
    int a, b, cost;
    bool viz = 0;
} muchii[400003];
vector<int> t;

bool cmp(muchie a, muchie b)
{
    return a.cost < b.cost;
}
int find_set(int nod)
{
    if (nod == t[nod])
        return nod;
    return t[nod] = find_set(t[nod]);
}
void union_sets(int a, int b)
{
    a = find_set(a), b = find_set(b);
    if (a != b)
        t[b] = a;
}
void kruskal()
{
    t.resize(n + 1);
    for (int i = 1; i <= n; i++)
        t[i] = i;
    sort(muchii + 1, muchii + m + 1, cmp);
    for (auto muchie : muchii)
        if (find_set(muchie.a) != find_set(muchie.b))
            union_sets(muchie.a, muchie.b),
                ctotal += muchie.cost, muchie.viz = 1;
}
int main()
{
    f >> n >> m;
    for (int i = 1, a, b, cost; i <= m; i++)
        f >> a >> b >> cost, muchii[i] = {a, b, cost};

    kruskal();

    g << ctotal << '\n';
    for (int i = 1; i <= m; i++)
        if (muchii[i].viz)
            rez++;

    g << rez << '\n';
    for (int i = 1; i <= m; i++)
        if (muchii[i].viz)
            g << muchii[i].a << " " << muchii[i].b << '\n';

    return 0;
}