Cod sursa(job #2796865)

Utilizator MihneaCadar101Cadar Mihnea MihneaCadar101 Data 8 noiembrie 2021 21:47:30
Problema Arbore partial de cost minim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("apm.in");
ofstream fout("apm.out");

struct elem {
    int nod1, nod2, cost;
};

const int nmax = 2e5 + 5;
int n, m, t[nmax], pret[nmax];
vector <elem> v;
vector <pair <int, int> > rasp;

elem make_elem(int x, int y, int c) {
    elem aux = {x, y, c};
    return aux;
}

bool cmp(elem a, elem b) {
    return a.cost < b.cost;
}

int findd(int x) {
    if (x != t[x]) return t[x] = findd(t[x]);

    return x;
}

void unite(int x, int y) {
    if (pret[x] < pret[y]) swap(x, y);

    t[y] = x;
    pret[x] += pret[y];
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        v.push_back(make_elem(x, y, c));
        t[x] = x;
        pret[x] = 1;
    }

    long long ans = 0;
    sort(v.begin(), v.end(), cmp);
    for (elem nr : v) {
        int nr1 = findd(nr.nod1);
        int nr2 = findd(nr.nod2);
        if (nr1 != nr2) {
            ans += nr.cost;
            unite(nr1, nr2);
            rasp.push_back({nr.nod1, nr.nod2});
        }
    }

    fout << ans << '\n' << rasp.size() << '\n';
    for (pair <int, int> x : rasp)
        fout << x.first << ' ' << x.second << '\n';
    return 0;
}