Cod sursa(job #1261403)

Utilizator deliaelena13Cirnu Delia deliaelena13 Data 12 noiembrie 2014 12:24:04
Problema Arbore partial de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <algorithm>
#define nmax 200001
#define mmax 400001

using namespace std;

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

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

muchie G[mmax];
int APM[nmax]; // retin indicii celor n-1 muchii selectate
int costAPM;
int conex[nmax]; // pt evidenta componentelor conexe

int m,n;

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

int main()
{
    int i;
    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; // la momentul initial fiecare varf apartine propriei comp conexe
}

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++)
    {
        if(conex[G[i].x]!=conex[G[i].y])
        {
            APM[++nrm]=i;
            costAPM+=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<<costAPM<<'\n';
    fout<<n-1<<'\n';
    for(i=1; i<=n-1; i++)
        fout<<G[APM[i]].x<<" "<<G[APM[i]].y<<'\n';
}