Cod sursa(job #2358830)

Utilizator VNohaiNohai Vlad-Auras VNohai Data 28 februarie 2019 13:14:03
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

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

#define NMAX 400001
#define MMAX 200001

int n, m, TT[NMAX], RG[NMAX], k=0, total;

struct muchie{int x, y, cost;} v[NMAX];
pair <int, int> p[MMAX];

bool compara(muchie a, muchie b)
{
    return a.cost<b.cost;
}

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

void citire()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
    fin>>v[i].x>>v[i].y>>v[i].cost;
    }
    sort(v+1, v+m+1, compara);
    for(int i=1; i<=n; i++)
    {
    TT[i]=i;
    RG[i]=1;
    }
}

void uneste(int x, int y)
{
     if(RG[x]<RG[y])
     {
     TT[x]=y;
     }
     else
     if(RG[x]>RG[y])
     {
     TT[y]=x;
     }
     else
     {
     TT[x]=y;
     RG[x]++;
     }
}

void rezolva()
{
     for(int i=1; i<=m; i++)
     {
     int fx, fy;
     fx=Find(v[i].x);
     fy=Find(v[i].y);
     if(fx!=fy)
     {
     uneste(fx, fy);
     k++;
     p[k].first=v[i].x;
     p[k].second=v[i].y;
     total+=v[i].cost;
     }
     }
}

void afis()
{
    fout<<total<<'\n';
    for(int i=1; i<=k; i++)
    {
    fout<<p[i].first<<" "<<p[i].second<<'\n';
    }
}

int main()
{
    citire();
    rezolva();
    afis();
    return 0;
}