Cod sursa(job #2867940)

Utilizator cdenisCovei Denis cdenis Data 10 martie 2022 17:18:21
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <forward_list>
#include <queue>

using namespace std;

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

const int MAX=1e5+5;
int n,m,a,b,c,t[MAX],cheie[MAX],viz[MAX],cost;
forward_list < pair < int, int > > v[MAX];

typedef pair < int, int > ip;
priority_queue < ip , vector < ip >, greater < ip > > pq;

int main()
{
    fin >> n >> m;
    for(;m;--m)
    {
        fin >> a >> b >> c;
        v[a].push_front(make_pair(b,c));
        v[b].push_front(make_pair(a,c));
    }
    for(int i=1;i<=n;i++)
        cheie[i]=1000000005;
    cheie[1]=0;
    pq.push(make_pair(0,1));
    while(!pq.empty())
    {
        int u=pq.top().second;
        pq.pop();
        viz[u]=1;
        for(auto vecin : v[u])
        {
            int nod=vecin.first;
            int cst=vecin.second;
            if(!viz[nod] && cst<cheie[nod])
            {
                t[nod]=u;
                cheie[nod]=cst;
                pq.push(make_pair(cheie[nod],nod));
            }
        }
    }
    for(int i=1;i<=n;i++)
        cost+=cheie[i];
    fout << cost << '\n' << n-1 << '\n';
    for(int i=2;i<=n;i++)
        fout << t[i] << " " << i << '\n';
    return 0;
}