Cod sursa(job #3258894)

Utilizator adimiclaus15Miclaus Adrian Stefan adimiclaus15 Data 24 noiembrie 2024 08:27:45
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 2e5;
const int INF = 1e9;
vector<pair<int, int>> G[NMAX + 1];
int d[NMAX + 1], p[NMAX + 1], vis[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;
    set<pair<int, int>> s; //(distanta, nod)
    s.insert({d[1], 1});
    int apm = 0;
    while(!s.empty()) {
        auto it = s.begin();
        s.erase(it);
        int node = (*it).second;
        int cost = (*it).first;
        if(vis[node]) {
            continue;
        }
        apm += cost;
        vis[node] = 1;
        for(auto it : G[node]) {
            int vecin = it.first;
            int costMuchie = it.second;
            if(!vis[vecin] && d[vecin] > costMuchie) {
                d[vecin] = costMuchie;
                s.insert({d[vecin], vecin});
                p[vecin] = node;
            }
        }
    }
    g << apm << '\n';
    g << n - 1 << '\n';
    for(int i = 2; i <= n; i++) {
        g << i << ' ' << p[i] << '\n';
    }
    return 0;
}