Cod sursa(job #3344567)

Utilizator aaa333aaa333 aaa333 Data 2 martie 2026 13:35:00
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

const int lim=400001;

pair <int,int> P[lim];
int k;
int N,M, total, tt[lim], rg[lim];

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

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

void citire()
{
    fin>>N>>M;
    for (int i=1; i<=M; i++)
        fin>>v[i].x>>v[i].y>>v[i].cost;
    sort(v+1, v+M+1, compare);
    for (int i=1; i<=N; i++)
    {
        tt[i]=i;
        rg[i]=1;
    }
}

int gaseste(int nod)
{
    while (tt[nod]!=nod)
    {
        nod=tt[nod];
    }
    return nod;
}

void unire(int x,int y)
{
    if (rg[x]<rg[y])
        tt[x]=y;
    if (rg[x]>rg[y])
        tt[y]=x;
    if (rg[x]==rg[y])
    {
        tt[x]=y;
        rg[y]++;
    }
}

void rezolva()
{
    for (int i=1; i<=N; i++)
    {
        int tatal_x=gaseste(v[i].x);
        int tatal_y=gaseste(v[i].y);
        if (tatal_x!=tatal_y)
        {
            unire(tatal_x, tatal_y);
            k++;
            P[k++].first=v[i].x;
            P[k].second=v[i].y;
            total=total+v[i].cost;
        }
    }
}

void afisare()
{
    fout<<total<<"\n";
    fout<<N-1<<"\n";

    for(int i=1; i<=k; i++)
        fout<<P[i].first<<" "<<P[i].second<<"\n";
}

int main()
{
    citire();
    rezolva();
    afisare();
    return 0;
}