Cod sursa(job #1376159)

Utilizator lacraruraduRadu Matei Lacraru lacraruradu Data 5 martie 2015 16:20:02
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>

#define N 50001
#define M 250001
#define INF 2147483647

using namespace std;

ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

int n, m;
int d[N];

int lst[N], vf[M], urm[M], cost[M], nvf = 0;

int h[N], poz[N], nh = 0;

void schimba(int i1, int i2)
{
    int aux = h[i1];
    h[i1] = h[i2];
    h[i2] = aux;
    poz[h[i1]] = i1;
    poz[h[i2]] = i2;
}

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

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

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

void sterge(int i)
{
    poz[h[i]] = 0;
    schimba(i, nh);
    nh--;
    urca(i);
    coboara(i);
}

void dijkstra(int x)
{
    for(int i = 1; i <= n; i++)
        d[i] = INF;
    d[x] = 0;
    adauga(x);

    while(nh)
    {
        x = h[1];
        sterge(1);

        for(int i = lst[x]; i; i = urm[i])
        {
            int y = vf[i];
            int c = cost[i];

            if(d[x] + c < d[y])
            {
                d[y] = d[x] + c;

                if(poz[y] == 0)
                    adauga(y);
                else
                    urca(poz[y]);
            }
        }
    }
}

int main()
{
    in >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;

        vf[++nvf] = y;
        cost[nvf] = c;
        urm[nvf] = lst[x];
        lst[x] = nvf;
    }

    dijkstra(1);

    for(int i = 2; i <= n; i++)
        out << d[i] << ' ';
    out << '\n';
    return 0;
}