Cod sursa(job #1587081)

Utilizator edim98Eduard Constantinescu edim98 Data 1 februarie 2016 19:55:25
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>
#define N 1000001
#define INF 2147483647

using namespace std;

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

struct nod
{
    int ind, cost;
    nod *next;
}*graf[N];

int n, m, d[N], Q[N];

void add(int x, int y, int c)
{
    if(graf[x] == NULL)
    {
        nod *p = new nod;
        p -> ind = x;
        p -> cost = 0;
        p -> next = NULL;
        graf[x] = p;
    }
    nod *nou = new nod, *p = graf[x];
    nou -> ind = y;
    nou -> cost = c;
    nou -> next = NULL;
    while(p -> next != NULL)
        p = p -> next;
    p -> next = nou;
}

void Read()
{
    int x, y, c;

    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        add(x, y, c);
    }
}

void Inf_vec()
{
    for(int i = 2; i <= n; i++)
        d[i] = INF;
}


void Print()
{
    for(int i = 2; i <= n; i++)
    {
        if(d[i] == INF)
            d[i] = 0;
        fout << d[i] << " ";
    }
}

void Dijkstra()
{
    int prim = 0, ultim = 1, curent;
    nod *p;
    Q[0] = 1;
    while(prim <= ultim)
    {
        curent = Q[prim++];
        p = graf[curent];
        while(p != NULL)
        {
            if(p -> cost + d[curent] <= d[p -> ind])
            {
                d[p -> ind] = p -> cost + d[curent];
                if(p -> ind != curent)
                    Q[ultim++] = p -> ind;
            }
            p = p -> next;
        }
    }
}

int main()
{
    Read();
    Inf_vec();
    Dijkstra();
    Print();
    return 0;
}