Cod sursa(job #3200957)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 6 februarie 2024 11:44:29
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
ifstream cin ("apm.in");
ofstream cout ("apm.out");
int n,m;
int rang[200005];
int rad[200005];
struct muchie
{
    int x,y,v;
};
muchie g[400005];
int radacina (int nod)
{
    int rasp = nod;
    while(rad[rasp]!=rasp)
        rasp = rad[rasp];
    int aux = nod;
    while(rad[nod]!=nod)
    {
        aux = rad[nod];
        rad[nod] = rasp;
        nod = aux;
    }
    return rasp;
}
void unire(int x,int y)
{
    if(rang[x] > rang[y])
    {
        rad[y] = x;
        return;
    }
    if(rang[y] > rang[x])
    {
        rad[x] = y;
        return;
    }
    rad[y] = x;
    rang[x]++;
}
bool fcmp(muchie a,muchie b)
{
    return a.v < b.v;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for(int i=1;i<=n;i++)
    {
        rad[i] = i;
        rang[i] = 1;
    }
    for(int i=1;i<=m;i++)
        cin >> g[i].x >> g[i].y >> g[i].v;
    sort(g+1,g+m+1,fcmp);
    int rasp = 0;
    vector< pair<int,int> > sol;
    for(int i=1;i<=m;i++)
    {
        pair<int,int> aux = {g[i].x,g[i].y};
        int x = radacina(g[i].x);
        int y = radacina(g[i].y);
        if(x==y)
            continue;
        rasp+=g[i].v;
        unire(x,y);
        sol.push_back(aux);
    }
    cout << rasp << '\n';
    cout << sol.size() << '\n';
    for(auto x:sol)
        cout << x.first << ' ' << x.second << '\n';
    return 0;
}