Cod sursa(job #1342013)

Utilizator lacraruraduRadu Matei Lacraru lacraruradu Data 13 februarie 2015 13:43:51
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <vector>

using namespace std;

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

struct muchie
{
    int y, c;
};


const int N = 50001;
const int INF = (1 << 31) - 1;

int n, m;
int d[N];
vector<muchie> a[N];

int h[N], poz[N], nh;
void schimba(int i1, int i2);
void urca(int i);
void coboara(int i);
void adauga(int x);
void sterge(int i);

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 / 2, i);
        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)
{
    schimba(i, nh);
    nh--;
    coboara(i);
    urca(i);
}


void citire()
{
    in >> n >> m;

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

        a[x].push_back((muchie){y, c});
    }
}


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

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

        for(size_t i = 0; i < a[x].size(); i++)
        {
            int y = a[x][i].y;
            int c = a[x][i].c;

            if(d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                if(poz[y] == 0)
                    adauga(y);
                else
                    urca(poz[y]);
            }
        }
    }
}


void afisare()
{
    for(int i = 2; i <= n; i++)
       if(d[i] == INF)
            out << 0 << ' ';
       else
            out << d[i] << ' ';

    out << '\n';
}

int main()
{
    citire();
    dijkstra(1);
    afisare();
    return 0;
}