Cod sursa(job #3214098)

Utilizator ana_valeriaAna Valeria Duguleanu ana_valeria Data 13 martie 2024 19:56:21
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <algorithm>
#define MAXN 200000
#define MAXM 400000
using namespace std;
ifstream cin ("apm.in");
ofstream cout ("apm.out");
struct ura
{
    int x, y, cost;
};
ura v[MAXM + 10], edges[MAXN + 10];
int boss[MAXN + 10], cnt[MAXN + 10];
bool cmp(const ura &a, const ura &b)
{
    if (a.cost < b.cost)
        return true;
    return false;
}
int finalBoss(int node)
{
    if (node == boss[node])
        return node;
    else
        return boss[node] = finalBoss(boss[node]);
}
void join(int node1, int node2)
{
    node1 = finalBoss(node1);
    node2 = finalBoss(node2);
    if (cnt[node1] > cnt[node2])
    {
        boss[node2] = node1;
        cnt[node1] = cnt[node1] + cnt[node2];
    }
    else
    {
        boss[node1] = node2;
        cnt[node2] = cnt[node2] + cnt[node1];
    }
}
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
        cin >> v[i].x >> v[i].y >> v[i].cost;
    sort(v + 1, v + m + 1, cmp);
    for (int i = 1; i <= n; i++)
    {
        boss[i] = i;
        cnt[i] = 1;
    }
    int cntEdges = 0, costMin = 0;
    for (int i = 1; i <= m && cntEdges < n - 1; i++)
        if (finalBoss(v[i].x) != finalBoss(v[i].y))
        {
            join(v[i].x, v[i].y);
            costMin = costMin + v[i].cost;
            cntEdges++;
            edges[cntEdges] = v[i];
        }
    cout << costMin << '\n' << n - 1 << '\n';
    for (int i = 1; i < n; i++)
        cout << edges[i].x << ' ' << edges[i].y << '\n';
    return 0;
}