Cod sursa(job #2340900)

Utilizator xAnonymouSxMandru Stefan xAnonymouSx Data 11 februarie 2019 11:06:25
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <algorithm>
#define NMAX 102
#define MMAX 5000

using namespace std;
ifstream fin("kruskal.in");
ofstream fout("kruskal.out");

struct muchie
{
    int x, y, c;
};
muchie g[MMAX];
int n, m, cost;
int conex[NMAX];///comp conexa din care face parte i
int a[NMAX];///indicii muchiilor selectate in arbore

void citire();
void kruskal();
void afisare();
void sortare();
bool compar(muchie, muchie);

int main()
{
    citire();
    kruskal();
    afisare();
    return 0;
}

void citire()
{
    fin>>n>>m;
    for (int i=1; i<=m; i++) fin>>g[i].x>>g[i].y>>g[i].c;
}

/*void sortare()
{
    int schimb;
    muchie aux;
    do
    {
        schimb=0;
        for (int i=1; i<=m; i++)
            if (g[i].c>g[i+1].c)
            {
                aux=g[i];
                g[i]=g[i+1];
                g[i+1]=aux;
                schimb=1;
            }

    }
    while (schimb);
}*/

void kruskal()
{
    int i, cx, cy, nrsel;
///ordonez muchiile crescator dupa cost
    //sortare();
    sort(g+1, g+m+1, compar);
    for (i=1; i<=n; i++) conex[i]=i;
    nrsel=0;
    i=1;
    while (nrsel<n-1)
    {
        if (conex[g[i].x]!=conex[g[i].y])
        {
            nrsel++;
            a[nrsel]=i;
            cost+=g[i].c;
            ///unificam comp conexe ale extremitatilor
            cx=conex[g[i].x];
            cy=conex[g[i].y];
            for (int j=1; j<=n; j++)
                if (conex[j]==cy) conex[j]=cx;
        }
        i++;
    }
}

void afisare()
{
    fout<<cost<<endl;
    for (int i=1; i<n; i++)
        fout<<g[a[i]].x<<' '<<g[a[i]].y<<endl;
}


bool compar(muchie A, muchie B)
{
    return A.c<B.c;
}