Cod sursa(job #3273544)

Utilizator vladm98Munteanu Vlad vladm98 Data 2 februarie 2025 16:28:26
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>

using namespace std;

int tata[100005], height[100005];

void reset(int n) {
    for (int i = 1; i <= n; i++) {
        tata[i] = i;
        height[i] = 1;
    }
}

int getRoot(int x) { // aproape O(1)
    int root = x;
    while (root != tata[root]) {
        root = tata[root];
    }
    // compresia drumurilor
    while (x != root) {
        int tx = tata[x];
        tata[x] = root;
        x = tx;
    }
    return root;
}

void unite(int x, int y) { // aproape O(1)
    x = getRoot(x);
    y = getRoot(y);

    if (height[x] < height[y]) {
        tata[x] = y;
    } else if (height[x] > height[y]) {
        tata[y] = x;
    } else { // egalitate
        tata[y] = x;
        height[x] += 1;
    }
}

vector <pair <int, pair <int, int>>> edges;
vector <pair <int, pair <int, int>>> chosenEdges;

int main()
{
    freopen("apm.in", "r", stdin);
    freopen("apm.out", "w", stdout);

    int n, m;
    int costTotal = 0;
    cin >> n >> m;
    reset(n);

    for (int i = 1; i <= m; i++) {
        int x, y, cost;
        cin >> x >> y >> cost;
        edges.push_back(make_pair(cost, make_pair(x, y)));
    }

    sort(edges.begin(), edges.end());

    for (auto edge: edges) {
        int x = edge.second.first;
        int y = edge.second.second;
        int cost = edge.first;

        if (getRoot(x) == getRoot(y)) continue; // daca se afla in aceeasi compo conexa, nu fac nimic

        unite(x, y);
        chosenEdges.push_back(make_pair(cost, make_pair(x, y)));
        costTotal += cost;
    }

    cout << costTotal << '\n';
    cout << chosenEdges.size() << '\n';

    for (auto edge: chosenEdges) {
        cout << edge.second.first << ' ' << edge.second.second << '\n';
    }
    return 0;
}