Cod sursa(job #2932936)

Utilizator dragosteleagaDragos Teleaga dragosteleaga Data 4 noiembrie 2022 12:29:17
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

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

struct muchie
{
    int from, to, cost;
    bool operator <(const muchie& a) const
    {
        return cost > a.cost;
    }
};

const int oo = 2e5 + 5;
int n, m, costmin;
vector<muchie> G[oo];
priority_queue<muchie> Q;
bool seen[oo];
vector< pair<int, int> > sol;

void Citire()
{
    fin >> n >> m;
    //G.resize(m);
    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >>c;
        muchie m;
        m.to = y;
        m.from = x;
        m.cost = c;
        G[x].push_back(m);
        m.to = x;
        m.from = y;
        G[y].push_back(m);
    }

}

void Prim()
{
    for(auto i : G[1])
        Q.push(i);
    seen[1] = 1;

    while(!Q.empty())
    {
        muchie m = Q.top();
        Q.pop();
        if(!seen[m.to])
        {
            seen[m.to] = 1;
            costmin += m.cost;
            sol.push_back({m.from, m.to});

            for(auto i : G[m.to])
                Q.push(i);
        }

    }
}

void Afisare()
{
    fout << costmin << "\n";
    fout << sol.size() << "\n";
    for(auto i : sol)
        fout << i.first << " " << i.second << "\n";
}

int main()
{

    Citire();
    Prim();
    Afisare();
    return 0;
}