Cod sursa(job #1574731)

Utilizator mihai.constantinConstantin Mihai mihai.constantin Data 20 ianuarie 2016 20:01:41
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

const int N_max = 50000;
const int M_max = 250000;
const int INF = 250000005;

int lst[N_max + 1];
int vf[M_max + 1];
int urm[M_max + 1];
int cost[M_max + 1];
int nr;

vector <int> C;
int d[N_max + 1];

int N, M;

void adauga(int x, int y, int c)
{
    //ADAUG IN LISTA LUI x PE y

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

int main()
{
    int i, x, y, c, p, u, poz, COST;

    in >> N >> M;

    for(i = 1; i <= M; i++)
    {
        in >> x >> y >> c;

        adauga(x, y, c);
    }

    for(i = 1; i <= N; i++) d[i] = INF;

    p = u = 0;

    //INSEREZ IN COADA NODUL DE START

    C.push_back(1);
    d[1] = 0;

    while(p <= u)
    {
        x = C[p++];

        //PARCURG VECINII y AI LUI x
        poz = lst[x];

        while(poz)
        {
            y = vf[poz];
            COST = cost[poz];

            if(d[y] > d[x] + COST)
            {
                u++;
                C.push_back(y);

                d[y] = d[x] + COST;
            }

            poz = urm[poz];
        }
    }

    for(i = 2; i <= N; i++)
    {
        if(d[i] == INF) d[i] = 0;

        out << d[i] << " ";
    }

    return 0;
}