Cod sursa(job #3210838)

Utilizator velciu_ilincavelciu ilinca velciu_ilinca Data 7 martie 2024 15:15:37
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;
ifstream in("apm.in");
ofstream out("apm.out");
const int nmax = 200001;
int n,m;
struct elem
{
    int inc,sf,price;
};
struct muchie
{
    int inc,sf;
};
elem v[nmax];
vector<muchie>muchii;
int tata[nmax];
int rang[nmax];
int cmp(elem a, elem b)
{
    return a.price < b.price;
}
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;
}