Cod sursa(job #3227626)

Utilizator gabriel.9619Gabriel Stefan Tita gabriel.9619 Data 2 mai 2024 12:02:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <algorithm>
#define dim 200001
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");

struct muchie{
    int x, y, cost, val;
}v[2*dim];

int cmp(muchie a, muchie b)
{
    return a.cost<b.cost;
}

int tata[dim];

int getroot(int nod)
{
    while(tata[nod]>0)
    {
        nod=tata[nod];
    }
    return nod;
}

int main()
{
    int n, m, i, nr=0, costmin=0;
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>v[i].x>>v[i].y>>v[i].cost;
    }
    for(i=1;i<=n;i++)
    {
        tata[i]=-1;
    }
    sort(v+1, v+m+1, cmp);
    i=1;
    nr=0;
    while(nr<n-1)
    {
        int x=v[i].x;
        int y=v[i].y;
        int rx=getroot(x);
        int ry=getroot(y);
        if(rx!=ry)
        {
            if(tata[rx]>tata[ry])
            {
                tata[ry]+=tata[rx];
                tata[rx]=ry;
            }
            else
            {
                tata[rx]+=tata[ry];
                tata[ry]=rx;
            }
            v[i].val=1;
            nr++;
            costmin+=v[i].cost;
        }
        i++;
    }
    fout<<costmin<<"\n"<<n-1<<"\n";
    for(i=1;i<=m;i++)
    {
        if(v[i].val==1)
        {
            fout<<v[i].x<<" "<<v[i].y<<"\n";
        }
    }
}