Cod sursa(job #3371396)

Utilizator Andreea345Vaduva Andreea Andreea345 Data 30 octombrie 2026 08:43:41
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX = 200001;
const int MMAX = 400001;

int p[NMAX], sz[NMAX];

struct muchie {
    int x, y, c;
};

muchie v[MMAX], sol[NMAX];

bool cmp(const muchie &a, const muchie &b) {
    return a.c < b.c;
}

int Find(int x) {
    int r = x;
    while (r != p[r]) {
        r = p[r];
    }
    while (x != r) {
        int nxt = p[x];
        p[x] = r;
        x = nxt;
    }
    return r;
}

void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    if (x == y) return;
    if (sz[x] < sz[y]) {
        p[x] = y;
        sz[y] += sz[x];
    } else {
        p[y] = x;
        sz[x] += sz[y];
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        p[i] = i;
        sz[i] = 1;
    }
    for (int i = 1; i <= m; ++i) {
        fin >> v[i].x >> v[i].y >> v[i].c;
    }
    sort(v + 1, v + m + 1, cmp);

    int apm = 0, nr = 0;
    for (int i = 1; i <= m; ++i) {
        if (Find(v[i].x) != Find(v[i].y)) {
            apm += v[i].c;
            Union(v[i].x, v[i].y);
            sol[++nr] = v[i];
        }
    }

    fout << apm << "\n" << nr << "\n";
    for (int i = 1; i <= nr; ++i) {
        fout << sol[i].x << " " << sol[i].y << "\n";
    }

    fin.close();
    fout.close();
    return 0;
}