Cod sursa(job #3214234)

Utilizator TonyyAntonie Danoiu Tonyy Data 13 martie 2024 21:56:21
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

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

const int N_Max = 2e5 + 1;
const int M_Max = 4e5 + 1;

int n, m, cost;

struct muchii
{
    int x, y, c;
} a[M_Max];

vector <int> tata(N_Max, -1), dim(N_Max, 1);
vector <pair <int, int>> b;

void read()
{
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
        fin >> a[i].x >> a[i].y >> a[i].c;
}

int find_set(int x)
{
    if (tata[x] == -1)
        return x;
    return tata[x] = find_set(tata[x]);
}

void union_sets(int x, int y)
{
    x = find_set(x);
    y = find_set(y);
    if (x == y)
        return;
    if (dim[x] < dim[y])
        swap(x, y);
    dim[x] += dim[y];
    tata[y] = x;
}

bool comp(muchii a, muchii b)
{
    return a.c < b.c;
}

void kruskal()
{
    sort(a + 1, a + m + 1, comp);

    for (int i = 1; i <= m; ++i)
    {
        if (find_set(a[i].x) != find_set(a[i].y))
        {
            union_sets(a[i].x, a[i].y);
            b.push_back({a[i].x, a[i].y});
            cost += a[i].c;
        }
    }
}

void print()
{
    fout << cost << "\n" << n - 1 << "\n";
    for (int i = 0; i < n - 1; ++i)
        fout << b[i].first << " " << b[i].second << "\n";
}

int main()
{
    read();
    kruskal();
    print();

    fin.close();
    fout.close();
    return 0;
}