Cod sursa(job #1587828)

Utilizator metrix007Lungu Ioan Adrian metrix007 Data 2 februarie 2016 17:02:12
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 50002
#define INF 5000
using namespace std;

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

struct graf
{
    int nod,c;
}pc,cod;

int n,m,grad,x,y,cost;
vector<graf> a[NMAX];
graf heap[NMAX];
int d[NMAX];
void sus(int x)
{
    while(heap[x/2].c>heap[x].c)
    {
        swap(heap[x/2],heap[x]);
    }
}

void jos(int x)
{
    while(heap[x].c > heap[x*2+1].c || heap[x].c>heap[x*2].c)
    {
        if(heap[x*2].c > heap[x*2+1].c)
        {
            swap(heap[x],heap[x*2+1]);
        }
        else
        {
            swap(heap[x],heap[x*2]);
        }
    }
}


graf Min()
{
    graf M = heap[1];
    if(grad>0)
        heap[1] = heap[grad--];
    jos(1);
    return M;
}

void Insert(graf a)
{
    heap[++grad] = a;
    sus(grad);
}

void dijkstra()
{

    for(int i=2;i<=n;i++)
        d[i] = INF;
    pc.c = 0; pc.nod = 1;
    Insert(pc);
    while(grad>0)
    {
        pc = Min();
        for(int i=0;i<a[pc.nod].size();i++)
        {
           //cout << pc.c;
            if(d[a[pc.nod][i].nod] > pc.c + a[pc.nod][i].c)
            {

                d[a[pc.nod][i].nod] = pc.c + a[pc.nod][i].c;
                cod.c = d[a[pc.nod][i].nod];
                cod.nod = a[pc.nod][i].nod;
                Insert(cod);
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i=0;i<m;i++)
    {
        in >> x >> y >> cost;
        pc.nod = y;
        pc.c = cost;
        a[x].push_back(pc);

    }
    dijkstra();
    for(int i=2;i<=n;i++)
        if(d[i]!=INF)
            out << d[i] << " ";
        else
            out << 0 << " ";

    return 0;
}