Cod sursa(job #2384588)

Utilizator PopescuAndreiAlexandruPopescu Andrei Alexandru PopescuAndreiAlexandru Data 20 martie 2019 21:47:19
Problema Arbore partial de cost minim Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <algorithm>

using namespace std;

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

const int nmax=400005;

pair <int,int> P[nmax];

int n,m,suma_cost,t[nmax],rg[nmax],a1,a2,cont=0;

struct muchii
{
    int x,y,cost;
}v[nmax];

bool comp(muchii a, muchii b)
{
    return a.cost<b.cost;
}

int Find(int nod)
{
    while(t[nod]!=nod)
        nod=t[nod];
    return nod;
}

void Union(int x, int y)
{
    if(rg[x]<rg[y])
        t[x]=y;
    if(rg[y]<rg[x])
        t[y]=x;
    if(rg[x]==rg[y])
    {
        t[x]=y;
        rg[y]++;
    }
}

void Sol()
{
    for(int i=1;i<=m;i++)
    {
        if(Find(v[i].x)!=Find(v[i].y))
        {
            Union(Find(v[i].x),Find(v[i].y));
            cont++;
            P[cont].first=v[i].x;
            P[cont].second=v[i].y;
            suma_cost+=v[i].cost;
        }
    }
}

int main()
{
    fin>>n>>m;
    for(int i=1;i<=m;i++)
        fin>>v[i].x>>v[i].y>>v[i].cost;
    for(int i=1;i<=m;i++)
    {
        t[i]=i;
        rg[i]=1;
    }
    sort(v+1,v+1+m,comp);
    Sol();
    fout<<suma_cost<<endl;
    fout<<n-1<<endl;
    for(int i=1;i<=cont;i++)
        fout<<P[i].first<<" "<<P[i].second<<endl;
}