Cod sursa(job #2120193)

Utilizator nicu_serteSerte Nicu nicu_serte Data 2 februarie 2018 01:34:39
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define mmax 400005
#define nmax 200005
struct muchie
{
    int x, y, c;
};
muchie L[mmax];
bool cmpf(muchie a, muchie b)
{
    return a.c<b.c;
}
int n, m, rang[nmax], t[nmax], index[nmax], cost;
void citire()
{
    int i;
    fin>>n>>m;
    for(i=1; i<=m; i++)
        fin>>L[i].x>>L[i].y>>L[i].c;
    fin.close();
}
void uneste(int x, int y)
{
    if(rang[x]<rang[y])
        t[x]=y;
    else t[y]=x;
}
int radacina(int x)
{
    int r, aux;
    r=x;
    while(r!=t[r])
        r=t[r];
    while(x!=t[x])
    {
        aux=t[x];
        t[x]=r;
        x=aux;
    }
    return r;
}
void Kruskal()
{
    int i, k;
    sort(L+1, L+1+m, cmpf);
    for(i=1; i<=n; i++)
        rang[i]=t[i]=i;
    i=k=1;
    while(i<=m && k<=n-1)
    {
        if(radacina(L[i].x)!=radacina(L[i].y))
        {
            uneste(radacina(L[i].x), radacina(L[i].y));
            cost+=L[i].c;
            index[k]=i;
            k++;
        }
        i++;
    }
}
void afisare()
{
    int i;
    fout<<cost<<'\n'<<n-1<<'\n';
    for(i=1; i<=n-1; i++)
        fout<<L[index[i]].x<<' '<<L[index[i]].y<<'\n';
    fout.close();
}
int main()
{
    citire();
    Kruskal();
    afisare();
    return 0;
}