Cod sursa(job #2909115)

Utilizator marateodorescu11Teodorescu Mara marateodorescu11 Data 9 iunie 2022 15:10:56
Problema Arbore partial de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
ifstream fin("apm.in");
ofstream fout("apm.out");

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

struct muchie
{
    int y, c;
};

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

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()
{
    int n, m;
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        a[x].push_back((muchie){y, c});
        a[y].push_back((muchie){x, c});
    }
    fin.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 (nu e primul drum pe care-l gasesc catre y)
                {
                    urca(poz[y]);///dar e cel mai scurt
                }
                else
                {
                    adauga(y);///y e unul dintre varfurile accesibile din 1 neprelucrate
                }
            }
        }
    }
    fout << cost << '\n' << n - 1 << '\n';
    for (int i = 2; i <= n; i++)
    {

        fout << pred[i] << " " << i << '\n';
    }
    fout.close();
    return 0;
}