Cod sursa(job #3155853)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 9 octombrie 2023 21:22:43
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

const int max_size = 2e5 + 1;

struct str{
    int x, y, val;
    bool operator < (const str & aux) const
    {
        return val < aux.val;
    }
};

int t[max_size];
vector <str> mc, apm;

int rad (int x)
{
    if (x == t[x])
    {
        return x;
    }
    return t[x] = rad(t[x]);
}

int main ()
{
    int n, m, ans = 0;
    in >> n >> m;
    while (m--)
    {
        int x, y, c;
        in >> x >> y >> c;
        mc.push_back({x, y, c});
    }
    for (int i = 1; i <= n; i++)
    {
        t[i] = i;
    }
    sort(mc.begin(), mc.end());
    for (auto f : mc)
    {
        if (rad(f.x) != rad(f.y))
        {
            t[rad(f.x)] = rad(f.y);
            ans += f.val;
            apm.push_back(f);
        }
    }
    out << ans << '\n' << n - 1 << '\n';
    for (auto f : apm)
    {
        out << f.x << " " << f.y << '\n';
    }
    in.close();
    out.close();
    return 0;
}