Cod sursa(job #1265197)

Utilizator AnaCucuAna Maria Cucu AnaCucu Data 16 noiembrie 2014 20:57:33
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include <algorithm>
#define MMAX 400000
#define NMAX 200001

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

struct Muchie
{
    int x, y;
    int cost;
};

Muchie G[MMAX];
int n, m;
int APM[NMAX], conex[NMAX];//indicii celor n-1 muchii selectate
int cost_apm;

void citire();
int compara(Muchie, Muchie);
void kruskal();
void afisare();

int main()
{
    citire();
    sort(G, G+m, compara);
    kruskal();
    afisare();
    return 0;
}

void citire()
{
    int i;
    fin >> n >> m;
    for(i=0; i <m; i++)
    {
        fin>>G[i].x>>G[i].y>>G[i].cost;
    }
    for(i=1; i<=n; i++)
        conex[i]=i;
}

int compara(Muchie a, Muchie b)
{
    return a.cost<b.cost;
}

void kruskal()
{
    int nrm=0, j, i, minim, maxim;
    for (i=0; nrm<n-1; i++)
    {
        //sunt acum la muchia i
        if (conex[G[i].x] != conex[G[i].y])
        {
            APM[++nrm]=i; //retin muchia
            cost_apm+=G[i].cost;
            if (conex[G[i].x]>conex[G[i].y])
            {
                minim=conex[G[i].y];
                maxim=conex[G[i].x];
            }
            else
            {
                minim=conex[G[i].x];
                maxim=conex[G[i].y];
            }
            for (j=1; j<=n; j++)
                if (conex[j]==maxim)
                    conex[j]=minim;
        }
    }
}

void afisare()
{
    int i;
    fout<<cost_apm<<'\n';
    fout<<n-1<<'\n';
    for (i=1; i<=n-1; i++)
        fout<<G[APM[i]].x<<' '<<G[APM[i]].y<<'\n';
}