Cod sursa(job #2974147)

Utilizator AlbuDariusAlbu Darius AlbuDarius Data 3 februarie 2023 12:59:06
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("kruskal.in");
ofstream fout("kruskal.out");
int viz[101], t[101], n, m, apm, a[2][101], l;
struct muchii
{
    int x, y, cost;
}v[5001];
bool mod(muchii a, muchii b)
{
    return a.cost < b.cost;
}
int cauta(int x)
{
    while (t[x] > 0)
        x = t[x];
    return x;
}
void kruskal();
int main()
{
    int i;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
        fin >> v[i].x >> v[i].y >> v[i].cost;
    kruskal();
    for (i = 1; i <= l; i++)
        fout << a[0][i] << " " << a[1][i] << "\n";
    return 0;
}
void kruskal()
{
    int i, x, y;
    for (i = 1; i <= n; i++)
        t[i] = -1;
    sort(v + 1, v + m + 1, mod);
    i = 0;
    while (l < n - 1) {
        x = cauta(v[++i].x);
        y = cauta(v[i].y);
        if (x != y) {
            a[0][++l] = v[i].x;
            a[1][l] = v[i].y;
            if (-t[x] >= -t[y]) {
                t[x] += t[y];
                t[y] = x;
            }
            else {
                t[y] += t[x];
                t[x] = y;
            }
            apm += v[i].cost;
        }
    }
    fout << apm << "\n";
}