Cod sursa(job #2758472)

Utilizator nicoleta_mnMartin nicoleta nicoleta_mn Data 10 iunie 2021 16:43:10
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

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

const int N = 2e5+10;
const int INF = 1e7 +10;

struct succesor
{
    int vf, c;
};

int d[N], h[N], poz[N], pred[N], n, m, nh, cost;
vector <succesor> a[N];
bitset<N>selectat;

void schimba(int p, int q)
{
    swap(h[p], h[q]);
    poz[h[p]] = p;
    poz[h[q]] = q;
}

void urca(int p)
{
    while (p > 1 && d[h[p]] < d[h[p/2]])
    {
        schimba(p, p/2);
        p /= 2;
    }
}

void coboara(int p)
{
    int fs = 2*p, fd = 2*p + 1, optim = p;
    if (fs <= nh && d[h[fs]] < d[h[optim]])
    {
        optim = fs;
    }
    if (fd <= nh && d[h[fd]] < d[h[optim]])
    {
        optim = fd;
    }
    if (optim != p)
    {
        schimba(p, optim);
        coboara(optim);
    }
}

void sterge(int p)
{
    if (p == nh)
    {
        nh--;
    }
    else
    {
        schimba(p, nh);
        poz[h[nh--]] = -1;
        urca(p);
        coboara(p);
    }
}

void apm()
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
        h[++nh] = i;
        poz[i] = nh;
    }
    d[1] = 0;
    urca(poz[1]);
    while (nh > 0)
    {
        int x = h[1];
        sterge(1);
        if(selectat[x])
        {
            continue;
        }
        cost += d[x];
        selectat[x] = true;
        for (auto p: a[x])
        {
            int y = p.vf;
            int c = p.c;
            if (!selectat[y] && c<d[y])
            {
                d[y] = c;
                pred[y] = x;
                urca(poz[y]);
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for (int i = 1; i<=m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back((succesor){y, c});
        a[y].push_back((succesor){x, c});
    }
    apm();
    out<<cost<<"\n"<<n-1<<"\n";
    for(int i=2;i<=n;i++)
    {
        out<<i<<" "<<pred[i]<<"\n";
    }
    return 0;
}