Cod sursa(job #3004565)

Utilizator velciu_ilincavelciu ilinca velciu_ilinca Data 16 martie 2023 13:47:28
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <vector>
#include <algorithm>

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

const int nmax = 200000;
int n,m;
struct elem
{
    int inc,sf,price;
};
elem v[nmax + 1];
int cmp(elem a, elem b)
{
    return a.price < b.price;
}
int tata[nmax + 1];
int rang[nmax + 1];
struct muchie
{
    int inc,sf;
};
vector<muchie>muchii;

void union1(int reprez1, int reprez2)
{
    if(rang[reprez1] == rang[reprez2])
    {
        tata[reprez1] = reprez2;
        rang[reprez2] ++;
    }
    else if(rang[reprez1] < rang[reprez2])
    {
        tata[reprez1] = reprez2;
    }
    else if(rang[reprez1] > rang[reprez2])
    {
        tata[reprez2] = reprez1;
    }
}
int find1(int x)
{
    int reprez = x;
    while(reprez != tata[reprez])
    {
        reprez = tata[reprez];
    }
    while(x != tata[x])
    {
        int father = tata[x];
        tata[x] = reprez;
        x = father;
    }
    return reprez;
}
int main()
{
    in>>n>>m;

    for(int i = 1; i <= n; i++)
    {
        tata[i] = i;
        rang[i] = 1;
    }

    for(int i = 1; i <= m; i++)
    {
        in>>v[i].inc>>v[i].sf>>v[i].price;
    }
    sort(v + 1, v + m + 1,cmp);

    int s = 0;

    for(int i = 1; i <= m; i++)
    {
        if(find1(v[i].inc) != find1(v[i].sf))
        {
            union1(find1(v[i].inc), find1(v[i].sf));
            s+= v[i].price;
            muchie newmuchie;
            newmuchie.inc = v[i].inc;
            newmuchie.sf = v[i].sf;
            muchii.push_back(newmuchie);

        }

    }
    out<<s<<'\n'<<muchii.size()<<'\n';
    for(int i = 0; i < muchii.size(); i++)
        out<<muchii[i].inc<<' '<<muchii[i].sf<<'\n';
    return 0;
}