Cod sursa(job #3376019)

Utilizator alex_0747Gheorghica Alexandru alex_0747 Data 15 noiembrie 2026 12:03:58
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#define INF (1<<20)
using namespace std;

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

int n, m, d[200005], p[200005];
bitset<200005> v;
vector<pair<int,int>> L[200005];

int main()
{
    int i, j, cost;
    priority_queue<pair<int, int>> q;
    vector<pair<int,int>> ans;

    fin >> n >> m;
    while (m--) {
        fin >> i >> j >> cost;
        L[i].push_back({j,cost});
        L[j].push_back({i,cost});
    }

    for (int i = 1; i <= n; i++) {
        d[i] = INF;
    }
    d[1] = 0;    
    v[1] = 1;
    for (const auto &[nod, cost] : L[1]) {
        d[nod] = cost;
        p[nod] = 1;
        q.push({-d[nod], nod});
    }
    cost = 0;
    for (int step = 2; step <= n; step++) {
        while (!q.empty() && v[q.top().second]) {
            q.pop();
        }
        auto [c, k] = q.top();
        q.pop();
        cost += d[k];
        v[k] = 1;
        for (const auto &[nod, cost] : L[k]) {
            if (!v[nod] && d[nod] > cost) {
                d[nod] = cost;
                p[nod] = k;
                q.push({-d[nod], nod});
            }
        }
    }

    fout << cost << "\n" << n - 1 << "\n";
    for (int i = 2; i <= n; i++) {
        fout << p[i] << " " << i << "\n";
    }
    return 0;
}