Cod sursa(job #3372948)

Utilizator VladPislaruPislaru Vlad Rares VladPislaru Data 5 noiembrie 2026 17:26:39
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>

using namespace std;


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

struct Muchie {
    int x, y, cost;

    bool operator < (const Muchie& A) const {
        return cost < A.cost;
    }
};

int n, m;
int viz[400005], t[200005];
vector<Muchie> M;


int Find(int x) {
    int rad, y;
    rad = x;
    while (t[rad] != 0) {
        rad = t[rad];
    }
    while (x != rad) {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}


void Union(int x, int y) {
    t[y] = x;
}



int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, cost;
        fin >> x >> y >> cost;
        M.push_back({x, y, cost});
    }
    sort(M.begin(), M.end());
    int cost = 0;
    for (int i = 0; i < m; i++) {
        int x = Find(M[i].x);
        int y = Find(M[i].y);
        if (x != y) {
            Union(x, y);
            cost += M[i].cost;
            viz[i] = 1;
        }
    }
    fout << cost << "\n";
    fout << n - 1 << "\n";
    for (int i = 0; i < m; i++)
        if (viz[i])
            fout << M[i].x << " " << M[i].y << "\n";
    return 0;
}