Cod sursa(job #3233975)

Utilizator rapidu36Victor Manz rapidu36 Data 5 iunie 2024 17:17:04
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 50000;
const int INF = 1 << 30;

struct succesor
{
    int varf, cost;
};

int h[N], d[N+1], poz[N+1], nh, n;
vector <succesor> 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 varf)
{
    h[nh] = varf;
    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);
}

void dijkstra(int x0)
{
    ///initializarea
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
        adauga(i);
    }
    d[x0] = 0;
    urca(poz[x0]);
    while (nh != 0 && d[h[0]] != INF)
    {
        int x = h[0];
        sterge(0);
        for (auto p: a[x])
        {
            int y = p.varf, c = p.cost;
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                urca(poz[y]);
            }
        }
    }
}

int main()
{
    ifstream in("dijkstra.in");
    ofstream out("dijkstra.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((succesor){y, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INF)
        {
            d[i] = 0;
        }
        out << d[i] << " ";
    }
    in.close();
    out.close();
    return 0;
}