Cod sursa(job #3371420)

Utilizator Andreea345Vaduva Andreea Andreea345 Data 30 octombrie 2026 09:33:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int NMAX = 200001;

vector<pair<int,int>> L[NMAX];
int d[NMAX], p[NMAX];
bool vis[NMAX];

int main() {
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        fin >> x >> y >> c;
        L[x].push_back({y, c});
        L[y].push_back({x, c});
    }
    for (int i = 1; i <= n; ++i) {
        d[i] = 1e9;
    }
    d[1] = 0;
    int apm = 0;

    // min-heap: (cost, nod)
    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
    pq.push({0, 1});

    while (!pq.empty()) {
        int cst = pq.top().first;
        int nod = pq.top().second;
        pq.pop();
        if (vis[nod]) continue;
        vis[nod] = 1;
        apm += cst;
        for (auto it : L[nod]) {
            int vec = it.first;
            int cost = it.second;
            if (vis[vec] == 0 && d[vec] > cost) {
                d[vec] = cost;
                p[vec] = nod;
                pq.push({cost, vec});
            }
        }
    }

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

    fin.close();
    fout.close();
    return 0;
}