Cod sursa(job #2723275)

Utilizator danhHarangus Dan danh Data 13 martie 2021 20:21:54
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int NMAX = 2e5+5;
const int inf = (1<<30);

int dist[NMAX], father[NMAX];

vector<pair<int, int> >v[NMAX];

vector<pair<int, int> > sol;

bitset<NMAX> viz;

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

int main()
{
    int c, n, m, i, j, x, y;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        v[x].push_back({y, c});
        v[y].push_back({x, c});
    }

    for(i=1; i<=n; i++)
    {
        dist[i] = inf;
    }


    for(auto el : v[1])
    {
        dist[el.first] = el.second;
        father[el.first] = 1;
        pq.push({el.second, el.first});
    }

    int apm_cost=0;

    viz[1] = 1;
    while(!pq.empty())
    {
        int nod = pq.top().second;
        c = pq.top().first;
        pq.pop();
        if(viz[nod])
            continue;
        viz[nod] = 1;

        apm_cost += c;
        sol.push_back({nod, father[nod]});

        for(auto el : v[nod])
        {
            if(!viz[el.first] && dist[el.first] > el.second)
            {
                dist[el.first] = el.second;
                father[el.first] = nod;
                pq.push({dist[el.first], el.first});

            }
        }

    }

    fout<<apm_cost<<'\n'<<sol.size()<<'\n';
    for(auto el : sol)
    {
        fout<<el.first<<' '<<el.second<<'\n';
    }

    fin.close();
    fout.close();
    return 0;

}