Cod sursa(job #3321872)

Utilizator CruduRazvanCrudu-Pivniceru Razvan CruduRazvan Data 11 noiembrie 2025 15:22:25
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
using namespace std;

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

struct M {
    int x, y, cost;
};

int parinte[200001], height[200001];

int Find(int x) {
    while (x != parinte[x]) {
        x = parinte[x];
    }
    return x;
}

int n, m, costT, nr;
vector<M> v;
vector<int> a[200001];

int main() {
    fin>>n>>m;
    for(int i=1; i<=m; i++) {
        M muchie;
        fin>>muchie.x>>muchie.y>>muchie.cost;
        v.push_back(muchie);
    }
    sort(v.begin(), v.end(), [](M a, M b) {
        return a.cost < b.cost;
    });

    for(int i=1; i<=n; i++) {
        parinte[i] = i;
        height[i] = 1;
    }
        for (int i = 0; i < m; i++) {
        int n1, n2, costn, x, y;
        n1 = v[i].x;
        n2 = v[i].y;
        costn = v[i].cost;
        x = Find(n1);
        y = Find(n2);
        if (x != y) {
            if (height[x] > height[y]) {
                parinte[y] = x;
            }
            else {
                if (height[x] < height[y]) {
                    parinte[x] = y;
                }
                else {
                    parinte[x] = y;
                    height[y]++;
                }
            }
            ++nr;
            a[nr].push_back(n1);
            a[nr].push_back(n2);
            costT += costn;
        }
    }
    fout<<costT<<'\n'<<nr<<'\n';
    for (int i = 1; i <= nr; i++) {
        fout<<a[i][1]<<" "<<a[i][0]<<'\n';
    }
    
    return 0;
}