Cod sursa(job #2270437)

Utilizator AlexTudorAlex Brinza AlexTudor Data 27 octombrie 2018 11:04:54
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>
using namespace std;

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

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

int const nmax=400005;
muchie a[nmax],sol[nmax];
int n,m;
int c,much;
int mult[nmax/2],sz[nmax/2];

bool comp(muchie a, muchie b)
{
    return (a.cost< b.cost) || (a.cost==b.cost && a.x<b.x) || (a.cost==b.cost && a.x==b.x && a.y<b.y);
}

void read()
{
    int i;
    fin>>n>>m;
    for(i=1;i<=m;++i)
    {
        fin>>a[i].x>>a[i].y>>a[i].cost;
    }
}

int Find(int val)
{
    int root=val;
    while(mult[root]!=root)
        root=mult[root];
    int aux;
    while(mult[val]!=root)
    {
        aux=mult[val];
        mult[val]=root;
        val=aux;
    }
    return root;
}

void Union(int a, int b)
{
    int rootA,rootB;
    rootA=Find(a);
    rootB=Find(b);
    if(sz[rootA]<sz[rootB])
    {
        sz[rootB]+=sz[rootA];
        mult[rootA]=rootB;
    }
    else
    {
        sz[rootA]+=sz[rootB];
        mult[rootB]=rootA;
    }
}

void solve()
{
    int i,x1,x2,m1,m2;
    sort(&a[1],&a[m+1],comp);

    for(i=1;i<=n;++i) {sz[i]=1; mult[i]=i;}

    for(i=1;i<=m && much<n-1;++i)
    {
        x1=a[i].x; x2=a[i].y;
        m1=Find(x1); m2=Find(x2);
        if(m1!=m2)
        {
            Union(x1,x2);
            c+=a[i].cost;
            much++;
            sol[much].x=x1; sol[much].y=x2;
        }
    }

    fout<<c<<"\n";
    fout<<n-1<<"\n";
    for(i=1;i<=n-1;++i) fout<<sol[i].y<<" "<<sol[i].x<<"\n";
}


int main()
{
    read();
    solve();
    return 0;
}