Cod sursa(job #3269618)

Utilizator game_difficultyCalin Crangus game_difficulty Data 20 ianuarie 2025 08:14:09
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;

ifstream cin("apm.in");
ofstream cout("apm.out");

struct muchie {
    int x, y, c;
    bool operator<(const muchie& other) {
        return c < other.c;
    }
};

muchie v[400005];
int c[200005];

int& componenta(int x) {
    while(c[x] != c[c[x]]) {
        c[x] = c[c[x]];
    }
    return c[x];
}

void connect(int x, int y) {
    componenta(componenta(x)) = componenta(y);
}

int main()
{
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        cin >> v[i].x >> v[i].y >> v[i].c;
    }
    for(int i = 1; i <= n; i++) c[i] = i;
    sort(v + 1, v + m + 1);
    int ans = 0;
    vector<pair<int, int> > mu;
    for(int i = 1; i <= m; i++) {
        if(componenta(v[i].x) != componenta(v[i].y)) {
            connect(v[i].x, v[i].y);
            ans += v[i].c;
            mu.push_back({v[i].x, v[i].y});
        }
    }
    cout << ans << '\n' << mu.size() <<'\n';
    for(pair<int, int> i : mu) {
        cout << i.first << ' ' << i.second << '\n';
    }
    return 0;
}