Cod sursa(job #3372932)

Utilizator TonyyAntonie Danoiu Tonyy Data 5 noiembrie 2026 16:47:44
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int nMax = 2e5 + 1;
const int Inf = 1 << 30;
vector<pair<int, int>> adj[nMax];
vector<int> dist(nMax, Inf), parent(nMax);
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
bitset<nMax> visited;
int mstCost;

void prim(int node) {
    dist[node] = 0;
    pq.push({0, node});  // cost, eticheta
    while (!pq.empty()) {
        auto [cost, node] = pq.top();
        pq.pop();
        if (visited[node]) {
            mstCost += cost;
        }
        visited[node] = 1;
        for (const auto& [neighbour, ncost] : adj[node]) {
            if (visited[neighbour] == 0 && ncost < dist[neighbour]) {
                dist[neighbour] = ncost;
                pq.push({ncost, neighbour});
                parent[neighbour] = node;
            }
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, z;
        fin >> x >> y >> z;
        adj[x].push_back({y, z});
        adj[y].push_back({x, z});
    }
    prim(1);
    fout << mstCost << "\n" << n - 1 << "\n";
    for (int i = 1; i <= n; i++) {
        if (parent[i]) {
            fout << i << " " << parent[i] << "\n";
        }
    }

    return 0;
}