Cod sursa(job #3215124)

Utilizator PalcPalcu Stefan Palc Data 14 martie 2024 18:11:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;

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

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

int n, m, cost_total;
int t[400005];
vrajeala L[400005];
vector<pair<int, int>> sol;

void Union(int x, int y)
{
    t[y] = x;
}

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

int main()
{
    int i, x, y;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
        fin >> L[i].x >> L[i].y >> L[i].cost;
    sort(L + 1, L + m + 1);
    for (i = 1; i <= m; i++)
    {
        x = Find(L[i].x);
        y = Find(L[i].y);
        if (x != y)
        {
            cost_total += L[i].cost;
            Union(x, y);
            sol.push_back({L[i].x, L[i].y});
        }
    }
    fout << cost_total << "\n";
    fout << sol.size() << "\n";
    for (pair<int, int> e : sol)
        fout << e.first << " " << e.second << "\n";
    return 0;
}