Cod sursa(job #3139698)

Utilizator Mihai_PopescuMihai Popescu Mihai_Popescu Data 30 iunie 2023 20:34:25
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

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

#define NMAX 400005

vector<pair<int, pair<int, int>>> G;
vector<pair<int, int>> muchii;

int tata[NMAX / 2], rang[NMAX / 2];

int radacina(int x)
{
    int parinte = x;

    while (tata[parinte] != parinte)
        parinte = tata[parinte];

    while (tata[x] != x)
    {
        int y = tata[x];
        tata[x] = parinte;
        x = y;
    }

    return parinte;
}

void uneste(int x, int y)
{
    if (rang[x] > rang[y])
        tata[y] = x;
    else
        tata[x] = y;

    if (rang[x] == rang[y])
        rang[y]++;
}

int main()
{
    int n, m;
    fin >> n >> m;

    for (int i = 0; i < m; ++i)
    {
        int x, y, c;
        fin >> x >> y >> c;
        G.push_back({c, {x, y}});
    }

    sort(G.begin(), G.end());

    for (int i = 1; i <= n; ++i)
    {
        tata[i] = i;
        rang[i] = 1;
    }

    int total = 0;

    for (int i = 0; i < m; ++i)
        if (radacina(G[i].second.first) != radacina(G[i].second.second))
        {
            total += G[i].first;

            muchii.push_back({G[i].second.first, G[i].second.second});

            uneste(radacina(G[i].second.first), radacina(G[i].second.second));
        }

    fout << total << '\n';
    fout << n - 1 << '\n';
    for (auto it : muchii)
        fout << it.first << ' ' << it.second << '\n';
    return 0;
}