Cod sursa(job #2980872)

Utilizator gabriel.9619Gabriel Stefan Tita gabriel.9619 Data 16 februarie 2023 21:19:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");

struct muchie{
    int x, y, cost, val;
}v[200001];

int tata[200001];

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

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

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