Cod sursa(job #2723254)

Utilizator CRazvaN6Cutuliga Razvan CRazvaN6 Data 13 martie 2021 19:58:01
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("apm.in");
ofstream g("apm.out");

int n,m,h[100010],tata[100010];
int radacina(int nod)
{
    int cpy = nod, aux;
    while(nod!=tata[nod]) nod = tata[nod];
    while(cpy != tata[nod]) aux = cpy, cpy = tata[cpy],tata[aux] = nod;
    return nod;
}
void unire(int nod1, int nod2)
{
    int r1 = tata[nod1];
    int r2 = tata[nod2];
    if(h[r1] < h[r2]) swap(r1,r2);
    h[r1] += h[r2];
    tata[r2] = r1;
}
struct data
{
    int x;
    int y;
    int cost;
};
vector<data> v;
int sorti(data a, data b)
{
    return a.cost < b.cost;
}
vector<pair<int,int> >ans;
int s;
int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x, y, c;
        f >> x >> y >> c;
        v.push_back({x,y,c});
    }
    sort(v.begin(), v.end(),sorti);
    for(int i = 1; i <= n; ++i)
    {
        tata[i] = i;
        h[i] = 1;
    }
    for(data p : v)
    {
        if(radacina(p.x) != radacina(p.y))
        {
            s += p.cost;
            unire(p.x,p.y);
            ans.push_back(make_pair(p.y,p.x));
        }
    }
    g << s << '\n';
    g << ans.size() << '\n';
    for(auto p : ans)
        g << p.first << " " << p.second << '\n';
    return 0;
}