Cod sursa(job #2357882)

Utilizator DenisPetreCsRekkles DenisPetre Data 27 februarie 2019 19:42:38
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#define NMax 400001

using namespace std;

ifstream f ("apm.in");
ofstream g ("apm.out");

pair <int, int > P[NMax];
int k;

struct muchie{
int x,y,cost;
} V[NMax];

int N,M,Total,RG[NMax],TT[NMax];

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

void citire()
{
   f>>N>>M;
   for(int i=1;i<=M;i++)
   {
       f>>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;
   }
}

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

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

void rezolva ()
{
    for(int i=1;i<=M;i++)
    {
        int tatal_x=Find(V[i].x);
        int tatal_y=Find(V[i].y);
        if(tatal_x!=tatal_y)
        {
            unire(tatal_x, tatal_y);
            P[++k].first=V[i].x;
            P[k].second=V[i].y;
            Total=Total+V[i].cost;
        }
    }
}

void afisare()
{
    g<<Total<<" ";
    g<<k<<"\n";
    for(int i=1;i<=k;i++)
    {
        g<<P[i].first<<" "<<P[i].second<<"\n";
    }
}
int main()
{
    citire();
    rezolva();
    afisare();
    return 0;
}