Cod sursa(job #3212399)

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