Cod sursa(job #3266851)

Utilizator inacioataCioata Ana Irina inacioata Data 10 ianuarie 2025 17:41:58
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, t[200005], costmin;

struct muchie
{
    int cost, ales, x, y;
    bool operator < (muchie e) const
    {
        return cost < e.cost;
    }
};
muchie a[400005];

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;
}

void Kruskal()
{
    int i, x, y;
    for(i = 1; i <= m; i++)
    {
        x = Find(a[i].x);
        y = Find(a[i].y);
        if(x != y)
        {
            Union(x, y);
            a[i].ales = 1;
            costmin += a[i].cost;
        }
    }
    fout << costmin << "\n" << n - 1 << "\n";
    for(i = 1; i <= m; i++)
        if(a[i].ales == 1) fout << a[i].x << " " << a[i].y << "\n";
}

int main()
{
    int i, x, y;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
        fin >> a[i].x >> a[i].y >> a[i].cost;
    sort(a + 1, a + m + 1);
    Kruskal();
    return 0;
}