Cod sursa(job #3335147)

Utilizator RaluccccaNegru Raluca Ralucccca Data 21 ianuarie 2026 18:40:21
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;

const int MAX = 20000;
const int INF = 1e9;
vector<pair<int, int> > G[MAX + 1], APM;
int d[MAX + 1], viz[MAX + 1], tata[MAX + 1];

int main() {
    ifstream fin("apm.in");
    ofstream fout("apm.out");
    int n, m, cost = 0;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
        G[y].push_back({x, c});
    }

    for (int i = 1; i <= n; i++) {
        d[i] = INF;
    }

    priority_queue<pair<int, int> > pq;
    d[1] = 0;
    pq.push({-d[1], 1});

    while (!pq.empty()) {
        pair<int, int> p = pq.top();
        pq.pop();
        int nod = p.second;

        if (viz[nod] == 0) {
            viz[nod] = 1;

            for (const auto &p: G[nod]) {
                int vecin = p.first;
                int cost = p.second;
                if (viz[vecin] == 0 && cost < d[vecin]) {
                    tata[vecin] = nod;
                    d[vecin] = cost;
                    pq.push({-d[vecin], vecin});
                }
            }
        }
    }
    for (int i = 1; i <= n; i++) {
        if (tata[i] != 0) {
            cost += d[i];
            APM.push_back({i, tata[i]});
        }
    }
    fout << cost << "\n";
    for (const auto &muchie: APM) {
        fout << muchie.first << " " << muchie.second << "\n";
    }

    return 0;
}