Cod sursa(job #2708559)

Utilizator Costea_AlexandruCostea Alexandru Costea_Alexandru Data 18 februarie 2021 21:49:51
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fi("apm.in");
ofstream fo("apm.out");
int n, m, i, j, k,cost, t[200001], rez[200001][3], rz;
vector<pair<int, int>>v[200001];
struct muchie { int x, y, z; } aux, aux2;
struct comp {
    bool operator()(muchie a, muchie b)
    {
        return (a.z > b.z);
    }
};
priority_queue<muchie,vector<muchie>,comp>q;
int Radacina(int x)
{
    if (t[x] == x)
        return x;
    else return t[x] = Radacina(t[x]);
}
int main()
{
    int nrm = 0;
    unsigned int a;
    fi >> n >> m;
    while (fi >> i >> j >> k)
    {
        v[i].push_back(make_pair(j, k));
        v[j].push_back(make_pair(i, k));
    }
    for (i = 1; i <= n; i++)
        t[i] = i;
    for (a = 0; a < v[1].size(); a++)
    {
        aux.x = 1;
        aux.y = v[1][a].first;
        aux.z = v[1][a].second;
        q.push(aux);
    }
    while (nrm < n - 1)
    {
        aux = q.top();
        q.pop();
        if (Radacina(aux.x) != Radacina(aux.y))
        {
            nrm++;
            rz++;
            rez[rz][1] = aux.x;
            rez[rz][2] = aux.y;
            cost += aux.z;
            t[Radacina(aux.y)] = Radacina(aux.x);
            for (a = 0; a < v[aux.y].size(); a++)
            {
                 aux2.x = aux.y;
                 aux2.y = v[aux.y][a].first;
                 aux2.z = v[aux.y][a].second;
                 q.push(aux2); 
            }
        }
    }
    fo << cost << '\n' << rz << '\n';
    for (i = 1; i <= rz; i++)
        fo << rez[i][1] << " " << rez[i][2] << '\n';
    return 0;
}