Cod sursa(job #3370594)

Utilizator Dimix12Miron Dimitrie Dimix12 Data 26 octombrie 2026 15:28:00
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
#include <fstream>
using namespace std;

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

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



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 sum = 0;
    for (int i = 1; i <=n; i++) {
        // selectam nodul cu d ul minim
        int nod = 0;
        int minim = 1e9;
        for (int j = 1; j <= n; j++) {
            if (vis[j] == 0 && d[j] < minim) {
                minim = d[j];
                nod = j;
            }
        }
        sum += d[nod];
        vis[nod] = 1;
        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;
            }
        }
    }
    fout << sum << '\n';
    fout << n-1 << '\n';
    for (int i = 2; i <= n; i++) {
        fout << i << " " << p[i] << '\n';
    }

}