Cod sursa(job #3205883)

Utilizator Mihai_PopescuMihai Popescu Mihai_Popescu Data 20 februarie 2024 20:03:39
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

#define NMAX 200005

vector<pair<int, int>> G[NMAX];
priority_queue<pair<int, pair<int, int>>> PQ;
vector<pair<int, int>> muchii;
bool viz[NMAX];
int cost;

void prim(int n) {
    for (auto it : G[1]) {
        PQ.push({-it.second, {it.first, 1}});
    }
    viz[1] = 1;

    int nr = 0;
    while (nr < n - 1) {
        auto aux = PQ.top();
        PQ.pop();

        int nod = aux.second.first;
        int prev = aux.second.second;

        if (!viz[nod]) {
            viz[nod] = 1;
            cost -= aux.first;
            nr++;

            muchii.push_back({nod, prev});

            for (auto it : G[nod]) {
                if (!viz[it.first]) {
                    PQ.push({-it.second, {it.first, nod}});
                }
            }
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    while (m--) {
        int x, y, c;
        fin >> x >> y >> c;

        G[x].push_back({y, c});
        G[y].push_back({x, c});
    }

    prim(n);

    fout << cost << '\n';
    fout << n - 1 << '\n';
    for (auto it : muchii) {
        fout << it.first << ' ' << it.second << '\n';
    }
    return 0;
}