Cod sursa(job #1979546)

Utilizator nicu_serteSerte Nicu nicu_serte Data 10 mai 2017 20:12:33
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>
#include <climits>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
#define nmax 50005
#define inf INT_MAX
int n, m, d[nmax], h;
vector<pair<int, int> > g[nmax];
struct nod
{
    int nod, cost;
};
nod heap[nmax];
void citire()
{
    int i, x, y, c;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>c;
        g[x].push_back(make_pair(y, c));
    }
    fin.close();
}
void afisare()
{
    for(int i=2; i<=n; i++)
        fout<<d[i]<<' ';
    fout<<'\n';
    fout.close();
}
void heapDown(int k)
{
    while((2*k<=n && heap[k].cost>heap[2*k].cost) || (2*k+1<=n && heap[k].cost>heap[2*k+1].cost))
    {
        if(2*k+1<=n && heap[2*k+1].cost<heap[2*k].cost)
        {
            swap(heap[k], heap[2*k+1]);
            k=2*k+1;
        }
        else
        {
            swap(heap[k], heap[2*k]);
            k=2*k;
        }
    }
}
nod extrage_min()
{
    nod k;
    k.nod=heap[1].nod;
    k.cost=heap[1].cost;
    heap[1]=heap[h];
    h--;
    heapDown(1);
    return k;
}
void heapUp(int k)
{
    while(k/2>0 && heap[k].cost<heap[k/2].cost)
    {
        swap(heap[k], heap[k/2]);
        k=k/2;
    }
}
void adauga(int nod, int cost)
{
    h++;
    heap[h].cost=cost;
    heap[h].nod=nod;
    heapUp(h);
}
void dijkstra(int p)
{
    vector<pair<int, int> >::iterator it;
    int i;
    nod k;
    bool viz[nmax]={0};
    for(i=1; i<=n; i++)
        d[i]=inf;
    d[p]=0;
    adauga(p, d[p]);
    viz[p]=1;
    while(h>0)
    {
        k=extrage_min();
        for(it=g[k.nod].begin(); it!=g[k.nod].end(); it++)
            if(d[it->first]>d[k.nod]+it->second)
            {
                d[it->first]=d[k.nod]+it->second;
                adauga(it->first, d[it->first]);
            }
    }
}
int main()
{
    citire();
    dijkstra(1);
    afisare();
    return 0;
}