Cod sursa(job #3370544)

Utilizator teobsnTeodor Bostan teobsn Data 26 octombrie 2026 14:54:15
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

const int NMAX = 2e5;
int p[NMAX + 1], sz[NMAX + 1];

int Find(int x)
{
    /*
        Return root of the tree x is part of
    */
    while (x != p[x])
        x = p[x];

    return x;
}

void Union(int x, int y)
{
    /*
        Make a union of the two trees (x and y are part of)
    */
    x = Find(x);
    y = Find(y);
    if (sz[x] > sz[y])
    {
        p[y] = x;
        sz[x] += sz[y];
    }
    else
    {
        p[x] = y;
        sz[y] += sz[x];
    }
}

bool commonRoot(int x, int y)
{
    return Find(x) == Find(y);
}

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

muchie v[400001], r[400001];

bool cmp(muchie a, muchie b) {
    return a.c < b.c;
}

int main()
{
    int n, m;

    fin >> n >> m;

    for (int i = 1; i <= n; i++)
    {
        p[i] = i;
        sz[i] = 1;
    }

    for (int i = 1; i <= m; i++)
    {
        fin >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v + 1, v + m + 1, cmp);

    int sum = 0;
    int nr = 0;
    for (int i = 1; i <= m; i++)
    {
        if (Find(v[i].x) != Find(v[i].y))
        {
            nr++;
            r[nr] = v[i];
            sum += v[i].c;
            Union(v[i].x , v[i].y);
        }
    }

    fout << sum << "\n" << nr << "\n";

    for (int i = 1; i <= nr; i++)
    {
        fout << r[i].y << " " << r[i].x << "\n";
    }

    return 0;
}