Cod sursa(job #1980002)

Utilizator nicu_serteSerte Nicu nicu_serte Data 11 mai 2017 21:22:15
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");
#define mmax 400005
#define nmax 200005
struct muchie
{
    int x, y, c;
}L[mmax];
int n, m, rang[nmax], t[nmax], cost;
vector<int> index;
bool cmpf(muchie a, muchie b)
{
    return a.c<b.c;
}
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();
}
int radacina(int x)
{
    int r, aux;
    r=x;
    while(t[r]!=r)
        r=t[r];
    while(t[x]!=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(L+1, L+1+m, cmpf);
    i=k=1;
    while(k<=n-1 && i<=m)
    {
        if(radacina(L[i].x)!=radacina(L[i].y))
        {
            uneste(radacina(L[i].x), radacina(L[i].y));
            k++;
            index.push_back(i);
            cost+=L[i].c;
        }
        i++;
    }
}
void afisare()
{
    vector<int>::iterator it;
    fout<<cost<<'\n'<<n-1<<'\n';
    for(it=index.begin(); it!=index.end(); it++)
        fout<<L[*it].x<<' '<<L[*it].y<<'\n';
    fout.close();
}
int main()
{
    citire();
    Kruskal();
    afisare();
    return 0;
}