Cod sursa(job #2844752)

Utilizator PopaMihaimihai popa PopaMihai Data 5 februarie 2022 12:44:05
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

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

struct str
{
    int cost;
    int node;
    int from;
};

const int NMAX = 2e5 + 2, INF = 1e9;

vector <pair <int, int>> G[NMAX];
int n, m, total;
int d[NMAX], T[NMAX];
bool sel[NMAX];

auto cmp = [](str a, str b)
{
    if (!(a.cost < b.cost))
        return 1;
    return 0;
};

priority_queue <str, vector <str> , decltype(cmp)> H(cmp);

void Init(int S)
{
    for(int i = 1; i <= n; ++ i)
        d[i] = INF;
    d[S] = 0;
    sel[S] = true;
    return;
}

void Prim(int S)
{
    Init(S);
    for(auto it: G[S]) {
        d[it.second] = (it.first < d[it.second] ? it.first : d[it.second]);
        H.push({it.first, it.second, S});
    }

    while(!H.empty()) {
        while(!H.empty() && sel[H.top().node])
            H.pop();
        if(H.empty())
            return;

        int node = H.top().node;
        int cost = H.top().cost;
        int from = H.top().from;

        total += cost;
        sel[node] = true;
        T[node] = from;
        H.pop();
        for(auto it: G[node]) {
            if(!sel[it.second])
                H.push({it.first, it.second, node});
        }
    }
}

int main()
{
    fin >> n >> m;
    int a, b, cost;
    for(int i = 1; i <= m; i++) {
        fin >> a >> b >> cost;
        G[a].push_back({cost, b});
        G[b].push_back({cost, a});
    }

    Prim(1);
    fout << total << '\n' << n - 1 << '\n';
    for(int i = 1; i <= n; ++i){
        if(i != 1)
            fout << i << " " << T[i] << '\n';
    }
    return 0;
}