Cod sursa(job #1366159)

Utilizator andreismara97Smarandoiu Andrei andreismara97 Data 28 februarie 2015 20:18:42
Problema Distante Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.96 kb
#include<fstream>
#include<vector>
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

#define Nmax 50001
#define INF ((1<<30)-1)

struct muchie
{
    int y, cost;
};

vector <muchie> a[Nmax];

int n, m;
int d[Nmax];
int h[Nmax], poz[Nmax], nh;

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 > 1 && 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, cost;
        in >> x >> y >> cost;

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

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 cost=a[x][i].cost;

            if(d[x] + cost < d[y])
            {
                d[y] = d[x] + cost;
                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;
}