Cod sursa(job #2909126)

Utilizator rapidu36Victor Manz rapidu36 Data 9 iunie 2022 16:21:51
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>
#include <vector>
#include <iostream>
#include <bitset>

using namespace std;

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

struct muchie
{
    int y, c;
};

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

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

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

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

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

void sterge(int p)
{
    if (p == nh)
    {
        nh--;
    }
    else
    {
        schimb(p, nh--);
        urca(p);
        coboara(p);
    }
}

int main()
{
    ifstream in("apm.in");
    ofstream out("apm.out");
    int n, 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});
    }
    in.close();
    adauga(1);
    for (int i = 2; i <= n; i++)
    {
        d[i] = INF;
    }
    int cost = 0;
    while (nh != 0)///cat timp heap-ul nu e vid (mai am vf. accesibile din 1 neprelucrate)
    {
        int x = h[1];
        in_apm[x] = 1;
        cost += d[x];
        sterge(1);
        for (auto e: a[x])
        {
            int y = e.y, c = e.c;
            if (!in_apm[y] && c < d[y])
            {
                d[y] = c;
                pred[y] = x;
                if (poz[y] != 0)///y este deja in heap
                {
                    urca(poz[y]);///am gasit o muchie mai ieftina care il leaga pe y de apm
                }
                else
                {
                    adauga(y);///y e unul dintre varfurile care pot fi conectate la apm printr-o muchie
                }
            }
        }
    }
    out << cost << "\n" << n - 1 << "\n";
    for (int i = 2; i <= n; i++)
    {
        out << pred[i] << " " << i << "\n";
    }
    out.close();
    return 0;
}