Cod sursa(job #2722502)

Utilizator danhHarangus Dan danh Data 12 martie 2021 21:45:58
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 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 n, m, i, x, y, c;

    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});
    }

    viz[1] = 1;

    int total = 0;
    while(!pq.empty())
    {
        x = pq.top().second;
        c = pq.top().first;
        pq.pop();

        if(viz[x])
            continue;
        viz[x] = 1;

        total += c;
        sol.push_back({x, father[x]});

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

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

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