Cod sursa(job #3252987)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 31 octombrie 2024 17:29:07
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1e5;
const int INF = 1e9;
vector<pair<int, int>> G[NMAX + 1];
int d[NMAX + 1], vis[NMAX + 1];
int p[NMAX + 1];

int main() {
    ifstream f("apm.in");
    ofstream g("apm.out");
    int n, m;
    f >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        G[x].push_back({y, c});
        G[y].push_back({x, c});
    }
    for(int i = 1; i <= n; i++) {
        d[i] = INF;
    }
    d[1] = 0;
    int apm = 0;
    for(int i = 1; i <= n; i++) {
        int minim = INF;
        int node = 0;
        for(int j = 1; j <= n; j++) {
            if(!vis[j] && d[j] < minim) {
                minim = d[j];
                node = j;
            }
        }
        apm += minim;
        vis[node] = 1;
        for(auto next : G[node]) {
            if(!vis[next.first] && d[next.first] > next.second) {
                d[next.first] = next.second;
                p[next.first] = node;
            }
        }
    }
    g << apm << '\n';
    g << n - 1 << '\n';
    for(int i = 2; i <= n; i++) {
        cout << i << ' ' << p[i] << '\n';
    }
    return 0;
}