Cod sursa(job #3293685)

Utilizator robert_dumitruDumitru Robert Ionut robert_dumitru Data 12 aprilie 2025 12:00:57
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
using namespace std;

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

struct Trei
{
    int x, y, cost;
    bool operator < (const Trei e) const
    {
        return cost < e.cost;
    }
};

int n, m;
int t[200005];
Trei muchii[400005];
vector<pair<int, int>> sol;

void Union(int x, int y)
{
    t[x] = y;
}
int FindRoot(int x)
{
    int y, rad = x;
    while (t[rad] != 0)
        rad = t[rad];
    while (x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

int main()
{
    int x, y, cost, costTotal;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
        fin >> muchii[i].x >> muchii[i].y >> muchii[i].cost;
    sort(muchii + 1, muchii + m + 1);
    for (int i = 1; i <= m; i++)
    {
        x = muchii[i].x; y = muchii[i].y; cost = muchii[i].cost;
        x = FindRoot(x); y = FindRoot(y);
        if (x != y)
        {
            Union(x, y);
            costTotal += cost;
            sol.push_back({muchii[i].x, muchii[i].y});
        }
    }
    fout << costTotal << "\n" << sol.size() << "\n";
    for (auto w : sol)
        fout << w.first << " " << w.second << "\n";
    return 0;
}