Cod sursa(job #1650115)

Utilizator killlerr1Chilom Mircea killlerr1 Data 11 martie 2016 16:39:29
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
using namespace std;

ifstream is("apm.in");
ofstream os("apm.out");

struct Edge {
    int x, y, w;
};

const int MaxN = 100, MaxM = 1000;
Edge e[MaxM];   // graful memorat ca sir de muchii
Edge apm[MaxN]; // APM -ul
int costAPM;
int m;  // nr muchii
int n;  // nr noduri
int comp[MaxN];  //  comp[i] = j plasam varful i in comp conexa j

void Read();
void Sort();
void Kruskal();
void WriteAPM();

int main()
{
    Read();
    Kruskal();
    WriteAPM();
    return 0;
}


void Kruskal()
{
    Sort(); // primul pas - sortarea muchiilor crescator dupa cost
    for (int i = 1; i <= n; ++i)
        comp[i] = i;

    int k = 0; // nr curent de muchii alese
    for (int i = 0; i < m; ++i)
    {
        int x = e[i].x, y = e[i].y;
        if ( comp[x] != comp[y] ) // aceasta muchie nu inchide ciclu
        {
            apm[k++] = e[i];
            costAPM += e[i].w;
            for (int j = 1; j <= n; ++j)
                if ( comp[j] == comp[y])
                    comp[j] = comp[x];
            if ( k == n - 1)
                break;
        }
    }
}

void Read()
{
    is >> n;
    while ( is >> e[m].x >> e[m].y >> e[m].w)
        m++;
}

void Sort()
{
    Edge aux;
    for (int i = 0; i < m; ++i)
        for (int j = i + 1; j < m; ++j)
            if ( e[i].w > e[j].w)
            {
                aux = e[i];
                e[i] = e[j];
                e[j] = aux;
            }
}

void WriteAPM()
{
    os << costAPM << '\n';
    for (int i = 0; i < n - 1; ++i)
        os << apm[i].x << ' ' << apm[i].y
           << ' ' << apm[i].w << '\n';
}