Cod sursa(job #1939106)

Utilizator RazvanRometeRomete Razvan Vasile RazvanRomete Data 25 martie 2017 14:20:57
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

struct muchie
{
    int s,d,c;
};

const int nn=200001;
const int nm=400001;

muchie a[nm],sol[nm];
int f[nn],h[nm],sum,m,n;

void read()
{
    fin>>n>>m;for(int i=1;i<=m;++i)fin>>a[i].s>>a[i].d>>a[i].c;
}

inline bool comp(muchie e1,muchie e2)
{
    return e1.c<e2.c?true:false;
}

int find(int x)
{
    while(f[x])x=f[x];return x;
}

void _union(int x,int y)
{
    if(h[x]>h[y])f[y]=x;else{f[x]=y;if(h[x]==h[y])++h[y];}
}

void kruskal()
{
    int i,nrm=0;
    for(i=1;i<=n;++i)h[i]=1;
    i=1;
    while(nrm<n-1)
    {
        int x,y;
        x=find(a[i].s);y=find(a[i].d);
        if(x!=y)
        {
            sol[++nrm]=a[i];
            sum+=a[i].c;
            _union(x,y);
        }
        ++i;
    }
}

int main()
{
    read();
    sort(a+1,a+1+m,comp);
    kruskal();
    fout<<n-1<<"\n"<<sum<<"\n";
    for(int i=1;i<n;++i)fout<<sol[i].d<<" "<<sol[i].s<<"\n";
}