Cod sursa(job #2728451)

Utilizator cdenisCovei Denis cdenis Data 23 martie 2021 11:55:26
Problema Arbore partial de cost minim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <forward_list>
#include <queue>

using namespace std;

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

int n,m,a,b,c,parent[200005],key[200005],viz[200005],weight;
forward_list < pair < int, int > > v[200005];

struct cmp
{
    bool operator()(int x,int y)
    {
        return key[x] > key[y];
    }
};

priority_queue < int, vector < int >, cmp > 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++)
        key[i]=1000000005;
    key[1]=0;
    pq.push(1);
    while(!pq.empty())
//    for(int cnt=1;cnt<n;cnt++)
    {
//        int mi=1000000005;
//        int u;
        int u=pq.top();
//        for(int i=1;i<=n;i++)
//            if(key[i]<mi && !viz[i])
//                mi=key[i], u=i;
        viz[u]=1;
        pq.pop();
        for(auto ngh : v[u])
            if(!viz[ngh.first] && ngh.second<key[ngh.first])
            {
                parent[ngh.first]=u;
                key[ngh.first]=ngh.second;
                pq.push(ngh.first);
            }
    }
    for(int i=1;i<=n;i++)
        weight+=key[i];
    fout << weight << '\n';
    fout << n-1 << '\n';
    for(int i=1;i<=n;i++)
        if(parent[i])
            fout << parent[i] << " " << i << '\n';
	return 0;
}