Cod sursa(job #3320169)

Utilizator iuliarusuIulia Rusu iuliarusu Data 4 noiembrie 2025 13:56:19
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("apm.in");
ofstream g("apm.out");

vector<pair<int, int>> L[200001];
priority_queue<pair<int,int>> pq;
int viz[200001],p[200001],d[200001];
int main(){
    int n,m;
    f >> n >> m;
    for (int i=1; i<=m;i++) {
        int x,y,c;
       f >> x >> y >> c;
        L[y].push_back({x,c});
        L[x].push_back({y,c});
    }
    for (int i=1; i<=n; i++) {
        d[i] = INT_MAX;
    }
    d[1] = 0;
    int sol = 0;
    pq.push({-d[1],1});
    while (pq.size() > 0) {
        int cost = -pq.top().first;
        int nod = pq.top().second;
        pq.pop();
        if(viz[nod] ==1) continue;
        viz[nod] = 1;
        sol+=cost;
        for (auto& x: L[nod]) {
            if (d[x.first] > x.second) {
                d[x.first] = x.second;
                pq.push({-d[x.first], x.first});
                p[x.first] = nod;
            }
        }
    }
    int p_length = 0;
    g << sol << "\n";
    for (int i=2; i<=n;i++) {
        if (p[i]!=0) {
            p_length++;
        }
    }
    cout << p_length << "\n";
    for (int i=2; i<=n; i++) {
        g << i << " " << p[i] << "\n";
    }
    return 0;
}