Cod sursa(job #3259967)

Utilizator Gabriel_DaescuDaescu Gabriel Florin Gabriel_Daescu Data 28 noiembrie 2024 16:41:15
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <algorithm>
#define MMAX 400002
#define NMAX 200002
using namespace std;
ifstream  fin("apm.in");
ofstream fout("apm.out");
int N,M,sef[NMAX],nr[NMAX],sol[NMAX],cnt,r;

struct triplet
{
    int x,y,c;
}v[MMAX];

void citire()
{
   fin>>N>>M;

   for(int i=1; i<=M; i++)
   {
       fin>>v[i].x>>v[i].y>>v[i].c;
   }
}

int cmp(triplet a, triplet b)
{
    if(a.c<b.c)
    {
        return 1;
    }
    return 0;
}

int cauta_sef(int poz)
{
    int z,p=poz;

    while(sef[p]!=p)
    {
        p=sef[p];
    }
    z=p;

    p=poz;
    while(sef[p]!=p)
    {
        int d=sef[p];
        sef[p]=z;
        p=d;
    }

    return z;
}

void afisare()
{
    fout<< r << "\n";
    fout<< N-1 << "\n";
    for(int i=1; i<=N-1; i++)
    {
        fout<< v[sol[i]].x << " " << v[sol[i]].y << "\n";
    }
}

int main()
{
    citire();

    sort(v+1,v+1+M,cmp);

    for(int i=1; i<=N; i++)
    {
        sef[i]=i;
        nr[i]=1;
    }

    cnt=r=0;
    for(int i=1; i<=M; i++)
    {
        int x=cauta_sef(v[i].x);
        int y=cauta_sef(v[i].y);
        if(x!=y)
        {
            r+=v[i].c;
            cnt++;
            sol[cnt]=i;

            if(nr[x]<nr[y])
            {
                sef[x]=y;
                nr[y]+=nr[x];
            }
            else
            {
                sef[y]=x;
                nr[x]+=nr[y];
            }
        }
    }

    afisare();

    return 0;
}