Cod sursa(job #3234897)

Utilizator rapidu36Victor Manz rapidu36 Data 12 iunie 2024 16:25:28
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.42 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 2e5;
const int INF = 1 << 10;

struct muchie
{
    int varf, cost;
};

int h[N], d[N+1], poz[N+1], pred[N+1], nh, n;
bool in_apm[N+1];
vector <muchie> a[N+1];

void schimba(int p1, int p2)
{
    swap(h[p1], h[p2]);
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}

int tata(int p)
{
    return ((p - 1) / 2);
}

int fiu_stang(int p)
{
    return (2 * p + 1);
}

int fiu_drept(int p)
{
    return (2 * p + 2);
}

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

void coboara(int p)
{
    int fs = fiu_stang(p), fd = fiu_drept(p), 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(optim, p);
        coboara(optim);
    }
}

void adauga(int pv)
{
    h[nh] = pv;
    poz[h[nh]] = nh;
    nh++;
    urca(nh - 1);
}

void sterge(int ph)
{
    if (ph == nh - 1)
    {
        nh--;
        return;
    }
    schimba(ph, nh - 1);
    nh--;
    urca(ph);
    coboara(ph);
}

int prim()
{
    ///initializarea
    in_apm[1] = false;
    d[1] = 0;
    adauga(1);
    pred[1] = 0;
    for (int i = 2; i <= n; i++)
    {
        in_apm[i] = false;
        d[i] = INF;
        adauga(i);
        pred[i] = 0;
    }
    int cost_total = 0;
    while (nh > 0)
    {
        int x = h[0];///varful cel mai "apropiat" de arborele construit pana acum
        cost_total += d[x];
        in_apm[x] = true;
        sterge(0);
        for (auto e: a[x])
        {
            int y = e.varf, c = e.cost;
            if (!in_apm[y] && c < d[y])
            {
                d[y] = c;
                pred[y] = x;
                urca(poz[y]);
            }
        }
    }
    return cost_total;
}

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