Cod sursa(job #2923465)

Utilizator gabriela.stanStan Luciana-Gabriela gabriela.stan Data 14 septembrie 2022 13:39:37
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define lung 200001
#define infinit 500000

using namespace std;

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

using pi = pair<int, int>;

struct comp
{
    bool operator()(pi a, pi b)
    {
        return a.second > b.second;
    }
};

int n, m, x, y, k, ctotal, nrm = -1;
vector<pi> v[lung];

void unif()
{
    for (int i = 1; i <= n; i++)
    {
        sort(v[i].begin(), v[i].end());
        v[i].resize(distance(v[i].begin(), unique(v[i].begin(), v[i].end())));
    }
}

bool viz[lung];
vector<int> parinte(lung, -1);
vector<int> cost(lung, infinit);
priority_queue<pi, vector<pi>, comp>
    pq;  //in pq se adauga toate muchiile care au un varf in apm-ul curent

void apm()
{
    pq.push(make_pair(1, 0));
    while (!pq.empty())
    {
        int nod1 = pq.top().first;
        int cost1 = pq.top().second;
        pq.pop();
        if (viz[nod1]) continue;
        viz[nod1] = 1;
        nrm++;
        ctotal += cost1;
        for (auto j : v[nod1])
        {
            int nod2 = j.first, cost2 = j.second;
            if (!viz[nod2] && cost[nod2] > cost2)
            {
                cost[nod2] = cost2;
                pq.push(make_pair(nod2, cost[nod2]));
                parinte[nod2] = nod1;
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y >> k;
        v[x].push_back(make_pair(y, k));
        v[y].push_back(make_pair(x, k));
    }
    unif();
    apm();
    fout << ctotal << " " << nrm << '\n';
    for (int i = 1; i <= n; i++)
    {
        if (parinte[i] > 0) fout << parinte[i] << " " << i << '\n';
    }
}