Cod sursa(job #3139684)

Utilizator Mihai_PopescuMihai Popescu Mihai_Popescu Data 30 iunie 2023 19:25:26
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

#define NMAX 200005

vector<pair<int, int>> G[NMAX];
priority_queue<pair<int, pair<int, int>>> PQ;
vector<pair<int, int>> muchii;
int viz[NMAX];

int main()
{
    int n, m;
    fin >> n >> m;

    while (m--)
    {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back({y, c});
        G[y].push_back({x, c});
    }

    for (auto it : G[1])
        PQ.push({-it.second, {it.first, 1}});
    viz[1] = 1;

    int nr = 0, total = 0;

    while (nr < n - 1)
    {
        auto next = PQ.top();
        PQ.pop();

        auto nod = next.second.first;
        auto prev = next.second.second;

        if (!viz[nod])
        {
            viz[nod] = 1;
            total -= next.first;
            nr++;

            muchii.push_back({nod, prev});

            for (auto it : G[nod])
                if (!viz[it.first])
                    PQ.push({-it.second, {it.first, nod}});
        }
    }

    fout << total << '\n';
    fout << n - 1 << '\n';
    for (auto it : muchii)
        fout << it.first << ' ' << it.second << '\n';
    return 0;
}