Cod sursa(job #3373203)

Utilizator CorvinJudge0Corvin Judge CorvinJudge0 Data 6 noiembrie 2026 12:28:32
Problema Arbore partial de cost minim Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstring>

using namespace std;

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

int n, m;

struct edge {
    int i, j, cost;
};

edge a[200001];
int t[200001];

int final_sum = 0;
int edgeCount = 0;

void read() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
        fin >> a[i].i >> a[i].j >> a[i].cost;
}

/// verif citire valori
void debug() {
    for (int i = 1; i <= m; i++)
        fout << a[i].i << " " << a[i].j << " " << a[i].cost << "\n";
}

bool cmp(edge x, edge y) {
    if (x.cost < y.cost) return true;
        else return false;
}

void init() {
    for (int i = 1; i <= n; i++) t[i] = i;
}

void reunion(int i, int j) {
    for (int k = 1; k <= n; k++) {
        if (t[k] == j) t[k] = i;
    }
}

int b[200001][3];

void APM() {
    for(int i = 1; i <= m ; i++)
        if(t[a[i].i] != t[a[i].j]) {
            final_sum += a[i].cost;
            int ii = t[a[i].i], jj = t[a[i].j];
            reunion(ii, jj);
            edgeCount++;
            b[edgeCount][1] = a[i].j;
            b[edgeCount][2] = a[i].i;
        }
}



int main()
{
    read();
    sort(a + 1, a + m + 1, cmp);
    init();
    APM();
    fout << final_sum << "\n" << edgeCount << "\n";
    for (int i = 1; i <= edgeCount; i++) {
        fout << b[i][2] << " " << b[i][1] << "\n";
    }
    //debug();

    return 0;
}