Cod sursa(job #3371407)

Utilizator Andreea345Vaduva Andreea Andreea345 Data 30 octombrie 2026 09:21:17
Problema Arbore partial de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <vector>
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;
    for (int i = 1; i <= n; ++i) {
        int mn = 1e9;
        int nod = 0;
        for (int j = 1; j <= n; ++j) {
            if (d[j] < mn && vis[j] == 0) {
                mn = d[j];
                nod = j;
            }
        }
        if (nod == 0) break;
        apm += 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 << apm << "\n" << n - 1 << "\n";
    for (int i = 2; i <= n; ++i) {
        fout << p[i] << " " << i << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}