Cod sursa(job #2340868)

Utilizator sunttttareTudor Popescu sunttttare Data 11 februarie 2019 10:30:42
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#define NMAX 200000
#define MMAX 400000

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

int n,m,cost,nrsel;
int conex[NMAX];
int A[NMAX];

struct muchie
{
int x,y,c;
}G[MMAX];

void citire();
void sortare();
void kruskal();
void afisare();

int main()
{
    citire();
    sortare();
    kruskal();
    afisare();
    return 0;
}

void citire()
{
    int i;
    fin>>n>>m;
    for (i=1;i<=m;i++)
        fin>>G[i].x>>G[i].y>>G[i].c;
    for (i=1;i<=n;i++)
        conex[i]=i;
}

void sortare()
{
    int ok=0,i;
    muchie aux;
    while(ok==0)
       {
        ok=1;
        for(i=1;i<=m-1;i++)
           {
            if(G[i].c>G[i+1].c)
              {
               aux=G[i+1];
               G[i+1]=G[i];
               G[i]=aux;
               ok=0;
              }
           }
       }
}

void kruskal()
{
    int i=1,j,cx,cy;
    while (nrsel<n-1)
          {
          if (conex[G[i].x]!=conex[G[i].y])
             {
             nrsel++;
             A[nrsel]=i;
             cost+=G[i].c;
             cx=conex[G[i].x];
             cy=conex[G[i].y];
             for (j=1;j<=n;j++)
                 if (conex[j]==cy) conex[j]=cx;
             }
          i++;
          }
}

void afisare()
{
    int i;
    fout<<cost<<'\n';
    for (i=1;i<=nrsel;i++)
        fout<<G[A[i]].x<<" "<<G[A[i]].y<<'\n';
}