Cod sursa(job #3284105)

Utilizator inacioataCioata Ana Irina inacioata Data 11 martie 2025 09:33:53
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include<bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
int n, m, t[100005], costmin, cnt;

struct muchie
{
    int x, y, cost, ales;
    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 x, y;
    for(int i = 1; i <= m; i++)
    {
        x = Find(a[i].x);
        y = Find(a[i].y);
        if(x != y)
        {
            Union(x, y);
            costmin += a[i].cost;
            a[i].ales = 1;
            cnt++;
        }
    }
    fout << costmin << "\n" << cnt << "\n";
    for(int i = 1; i <= m; i++)
        if(a[i].ales == 1) fout << a[i].x << " " << a[i].y << "\n";
}

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