Cod sursa(job #2176376)

Utilizator nicu_serteSerte Nicu nicu_serte Data 17 martie 2018 00:07:36
Problema Arbore partial de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define nmax 200005
#define mmax 400005
struct muchie
{
    int x, y, c;
}v[mmax];
bool cmpf(muchie a, muchie b)
{
    return a.c<b.c;
}
int n, m, rang[nmax], t[nmax], cost, id[mmax];
void citire()
{
    int i;
    fin>>n>>m;
    for(i=1; i<=m; i++)
        fin>>v[i].x>>v[i].y>>v[i].c;
    fin.close();
}
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 uneste(int x, int y)
{
    if(rang[x]<rang[y])
        t[x]=y;
    else t[y]=x;
}
void Kruskal()
{
    int i, k;
    for(i=1; i<=n; i++)
        rang[i]=t[i]=i;
    sort(v+1, v+1+m, cmpf);
    k=i=1;
    while(k<=n-1 && i<=m)
    {
        if(radacina(v[i].x)!=radacina(v[i].y))
        {
            uneste(v[i].x, v[i].y);
            cost+=v[i].c;
            id[k]=i;
            k++;
        }
        i++;
    }
}
void afisare()
{
    int i;
    fout<<cost<<'\n'<<n-1<<'\n';
    for(i=1; i<=n-1; i++)
        fout<<v[id[i]].x<<' '<<v[id[i]].y<<'\n';
    fout.close();
}
int main()
{
    citire();
    Kruskal();
    afisare();
    return 0;
}