Cod sursa(job #3375054)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 10 noiembrie 2026 03:08:44
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

int main() {
    ifstream fin("apm.in");
    ofstream fout("apm.out");
    int n, m;
    fin >> n >> m;
    vector<vector<pair<int, int> > > g(n + 1);
    for (int i = 0; i < m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        g[x].push_back(make_pair(y, c));
        g[y].push_back(make_pair(x, c));
    }
    vector<int> d(n + 1, INT_MAX), par(n + 1, 0);
    vector<bool> in(n + 1, false);
    priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
    d[1] = 0;
    pq.push(make_pair(0, 1));
    long long total = 0;
    while (!pq.empty()) {
        int c = pq.top().first, u = pq.top().second;
        pq.pop();
        if (in[u]) continue;
        in[u] = true;
        total += c;
        for (size_t i = 0; i < g[u].size(); i++) {
            int v = g[u][i].first, w = g[u][i].second;
            if (!in[v] && w < d[v]) {
                d[v] = w;
                par[v] = u;
                pq.push(make_pair(w, v));
            }
        }
    }
    fout << total << '\n' << n - 1 << '\n';
    for (int i = 2; i <= n; i++) fout << par[i] << ' ' << i << '\n';
    return 0;
}