Cod sursa(job #2537326)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 3 februarie 2020 16:06:57
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 2e5 + 5;

int Size[N], parent[N];

void make_set(int k)
{
    Size[k] = 1;
    parent[k] = k;
}

int find_set(int k)
{
    if(parent[k] != k) return parent[k] = find_set(parent[k]);
    return k;
}

void union_sets(int a, int b)
{
    a = find_set(a), b = find_set(b);
    if(a != b) {
        if(Size[b] > Size[a]) swap(a, b);
        Size[a] += Size[b];
        parent[b] = a;
    }
}

struct solve
{
    int x, y, w;

    bool operator < (const solve & nxt) const
    {
        return w < nxt.w;
    }
};

vector < solve > edges;
vector < pair < int, int > > sol;

int main()
{
    usain_bolt();

    int n, m;

    fin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y, w;

        fin >> x >> y >> w;
        edges.push_back({x, y, w});
    }
    sort(edges.begin(), edges.end());

    for(int i = 1; i <= n; ++i) make_set(i);
    int ans = 0;
    for(auto x : edges) {
        if(find_set(x.x) != find_set(x.y)) {
            union_sets(x.x, x.y);
            ans += x.w;
            sol.push_back({x.x, x.y});
        }
    }
    fout << ans << "\n";
    fout << sol.size() << "\n";
    for(auto v : sol) fout << v.first << " " << v.second << "\n";
    return 0;
}