Cod sursa(job #2829911)

Utilizator cyg_Alex_codegicianBarbu Alexandru cyg_Alex_codegician Data 9 ianuarie 2022 10:00:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
const int nmax=200005, mmax=400005;
int n, m, tt[nmax], rg[nmax], cost;
vector <pair<int, int>> rez;
ifstream fin("apm.in");
ofstream fout("apm.out");
struct muchie
{
    int x, y, c;
}v[mmax];
bool cmp(muchie a, muchie b)
{
    return a.c < b.c;
}
int findset(int nod)
{
    while (tt[nod] != nod)
        nod = tt[nod];
    return nod;
}
void unionset(int x, int y)
{
    if (rg[x]<rg[y])
        tt[x]=y;
    else if (rg[y]<rg[x])
        tt[y]=x;
    else
    {
        tt[x]=y;
        rg[y]++;
    }
}
void apm()
{
    for (int i=1; i<=m; i++)
    {
        int ttx=findset(v[i].x);
        int tty=findset(v[i].y);
        if (ttx!=tty)
        {
            unionset(ttx, tty);
            rez.push_back(make_pair(v[i].x, v[i].y));
            cost+=v[i].c;
        }
    }
}
int main()
{
    fin >> n >> m;
    for (int i=1; i<=m; i++)
    {
        fin >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v+1, v+m+1, cmp);
    for (int i=1; i<=n; i++)
    {
        tt[i]=i;
        rg[i]=1;
    }
    apm();
    fout << cost << '\n';
    fout << n-1 << '\n';
    for (int i=0; i<n-1; i++)
    {
        fout << rez[i].first << " " << rez[i].second << '\n';
    }
    return 0;
}