Cod sursa(job #2525999)

Utilizator Catalin_GriuGriu Catalin Catalin_Griu Data 18 ianuarie 2020 10:30:55
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <queue>
#define NMAX 200002
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");


struct muchie{
    int x, y, cost;
    friend bool operator > (muchie, muchie);
};

bool operator> (muchie a, muchie b){
    return a.cost>b.cost;   }

priority_queue<muchie, vector<muchie>, greater<muchie> > H;

int n, m, costmin;
int tata[NMAX];
int h[NMAX];
muchie sel[NMAX];

int Find(int x);
void Union(int x, int y);
void  citire();
void afisare();
void kruskal();

int main()
{
    citire();

    kruskal();

    afisare();
    return 0;
}

void  citire()
{
    muchie a;

    fin>>n>>m;

    for(int i = 0; i<m; i++)
    {
        fin>>a.x>>a.y>>a.cost;
        H.push(a);
    }
}

int Find(int x)
{
    int rad = x, y;

    while(tata[rad]) rad = tata[rad];

    while(tata[x])
    {
        y = tata[x]; tata[x] = rad;
        x = y;
    }

    return rad;
}

void Union(int x, int y)
{
    x = Find(x); y = Find(y);
    if(h[x] > h[y])
        tata[y] = x;
    else
    {
        tata[x] = y;
        if(h[x] == h[y]) h[y]++;
    }
}

void kruskal()
{
    muchie a;
    int nrsel = 0, c1, c2;
    while(nrsel<n-1)
    {
        a = H.top();    H.pop();
        c1 = Find(a.x); c2 = Find(a.y);
        if(c1 != c2)
        {
            sel[nrsel++] = a;
            costmin += a.cost;
            Union(c1, c2);
        }
    }

}

void afisare(){
    fout<<costmin<<'\n'<<n-1<<'\n';
    for(int i = 0; i<n-1; i++)
        fout<<sel[i].x<<' '<<sel[i].y<<'\n';
}