Cod sursa(job #2348589)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 19 februarie 2019 20:29:28
Problema Arbore partial de cost minim Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 200005;

struct muchie
{
    int from, to, cost;

    bool operator < (const muchie other) const
    {
        return this->cost > other.cost;
    }
};

int N, M;
vector < pair<int, int> > G[NMAX];

bool chosen[NMAX];
priority_queue <muchie> pq;
vector <muchie> apmEdges;
long long apmCost;

int main()
{
    int x, y, c;

    fin >> N >> M;

    for(int i = 1; i <= M; i++)
    {
        fin >> x >> y >> c;

        G[x].push_back(make_pair(y, c));
        G[y].push_back(make_pair(x, c));
    }

    chosen[1] = true;

    for(auto it : G[1])
        pq.push({1, it.first, it.second});

    for(int i = 2; i <= N; i++)
    {
        while(chosen[pq.top().to] != false)
            pq.pop();

        muchie mc = pq.top();
        apmCost += mc.cost;
        chosen[mc.to] = true;
        apmEdges.push_back(mc);

        for(auto it : G[mc.to])
            if(chosen[it.first] == false)
                pq.push({mc.to, it.first, it.second});
    }

    fout << apmCost << '\n' << N - 1 << '\n';
    for(auto it : apmEdges)
        fout << it.from << ' ' << it.to << '\n';

    return 0;
}