Cod sursa(job #2857406)

Utilizator Rares1707Suchea Rares-Andrei Rares1707 Data 25 februarie 2022 15:41:14
Problema Arbore partial de cost minim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int MAX = 100005, INF = (1 << 30);

int n, m;
int costNod[MAX], tata[MAX]; int costTotal = 0;
bool inArbore[MAX];

struct Compara
{
    bool operator() (pair < int, int > x, pair < int, int > y)
    {
        return (x.second > y.second);
    }
};

priority_queue < pair < int, int >, vector < pair < int, int > >, Compara > heap;

queue < pair < int, int > > drum[MAX];

void Citire()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        drum[x].push(make_pair(y, cost));
        drum[y].push(make_pair(x, cost));
    }
}

void Prim()
{
    for (int i = 2; i <= n; i++)
    {
        costNod[i] = INF;
    }
    heap.push(make_pair(1, 0));

    while(!heap.empty())
    {
        int nodActual = heap.top().first;
        heap.pop();

        if (!inArbore[nodActual])
        {
            inArbore[nodActual] = true;
            while (!drum[nodActual].empty())
            {
                int nodUrmator = drum[nodActual].front().first;
                int cost = drum[nodActual].front().second;
                drum[nodActual].pop();

                if (!inArbore[nodUrmator])
                {
                    if (cost < costNod[nodUrmator])
                    {
                        heap.push(make_pair(nodUrmator, cost));
                        costNod[nodUrmator] = cost;
                        tata[nodUrmator] = nodActual;
                    }
                }
            }

        }
    }
}

void Afisare()
{
    for (int i = 2; i <= n; i++)
    {
        costTotal += costNod[i];
    }
    fout << costTotal << '\n';
    fout << n - 1 << '\n';
    for (int i = 2; i <= n; i++)
    {
        fout << i << ' '  << tata[i] << '\n';
    }
}

int main()
{
    Citire();
    Prim();
    Afisare();
    return 0;
}