Cod sursa(job #2758463)

Utilizator BogdanFarcasBogdan Farcas BogdanFarcas Data 10 iunie 2021 16:15:04
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

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

const int N = 2e5+1;
const int INF = 1e9 + 1;

struct succesor
{
    int vf, c;
};

int d[N], h[N], poz[N], pred[N], n, m, nh, cost;
vector <succesor> s[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 Prim(int x0)
{
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
        h[++nh] = i;
        poz[i] = nh;
    }
    d[x0] = 0;
    urca(poz[x0]);
    while (nh > 0)
    {
        int x = h[1];
        sterge(1);
        if(selectat[x])
        {
            continue;
        }
        cost += d[x];
        selectat[x] = true;
        for (auto p: s[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()
{
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        s[x].push_back((succesor){y, c});
        s[y].push_back((succesor){x, c});
    }
    Prim(1);
    cout<<cost<<"\n"<<n-1<<"\n";
    for(int i=2;i<=n;i++)
    {
        cout<<i<<" "<<pred[i]<<"\n";
    }
    return 0;
}