Cod sursa(job #2173349)

Utilizator razvan99hHorhat Razvan razvan99h Data 15 martie 2018 21:46:26
Problema Arbore partial de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define DM 200005
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");

int n, m, a, b, c, viz[DM], arb[DM], cost_total, dim;
priority_queue <pair <int, pair <int, int> > > pq; /// -cost, nod, venit_din
vector <pair <int, int> > g[DM];

void make_apm()
{
    pq.push(make_pair(0, make_pair(1, 0)));
    while(!pq.empty())
    {
        int nod = pq.top().second.first;
        int venit_din = pq.top().second.second;
        int cost = -pq.top().first;
        pq.pop();

        if(!viz[nod])
        {
            viz[nod] = 1;
            arb[nod] = venit_din;
            cost_total += cost;
            for(auto it : g[nod])
                if(!viz[it.first])
                    pq.push(make_pair( -it.second, make_pair(it.first, nod)));
        }
    }
}
int main ()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> a >> b >> c;
        g[a].push_back(make_pair(b, c));
        g[b].push_back(make_pair(a, c));
    }
    make_apm();

    fout << cost_total << '\n';
    fout << n - 1 << '\n';
    for(int i = 2; i <= n; i++)
        fout << i << ' ' << arb[i] << '\n';

    return 0;
}