Cod sursa(job #3221583)

Utilizator vladdobro07vladdd vladdobro07 Data 7 aprilie 2024 15:07:18
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 2e5;

struct DSU {
    vector<int> t;
    DSU(const int n = nmax) {
        t.resize(n + 1);
        for(int i = 1; i <= n; i++)
            t[i] = i;
    }
    int parent(int x) {
        if(x == t[x])
            return x;
        else
            return t[x] = parent(t[x]);
    }
    bool joined(int x, int y) {
        int tx = parent(x), ty = parent(y);
        if(tx == ty)
            return 0;
        t[tx] = ty;
        return 1;
    }
};

vector<pair<int, pair<int, int>>> edge, sol;
DSU dsu;

int n, m, x, y, c, S = 0, E = 0;

void read() {
    fin >> n >> m;
    for(int i = 0; i < m; i++) {
        fin >> x >> y >> c;
        edge.push_back({c, {x, y}});
    }
}

void make_apm() {
    for(int i = 0; i < m; i++) {
        x = edge[i].second.first;
        y = edge[i].second.second;
        c = edge[i].first;
        if(dsu.joined(x, y)) {
            S += c;
            E++;
            sol.push_back(edge[i]);
        }
    }
}

void print() {
    fout << S << "\n" << E << "\n";
    for(auto putza : sol)
        fout << putza.second.first << " " << putza.second.second << "\n";
}

int main() {
    read();
    sort(edge.begin(), edge.end());
    make_apm();
    print();
    return 0;
}