Cod sursa(job #1810000)

Utilizator radu.leonardoThe Doctor radu.leonardo Data 19 noiembrie 2016 15:03:30
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
#define buff_size 104576
char buff[buff_size];
int pos=0;

inline void read(int &nr)
{
    while(!isdigit(buff[pos])) if(++pos == buff_size) fread(buff,  1,buff_size, stdin), pos = 0;
    nr = 0;
    while(isdigit(buff[pos]))
    {
        nr = (nr<<1)+(nr<<3)+ buff[pos] - 48;
        if(++pos == buff_size) fread(buff, 1, buff_size, stdin), pos = 0;
    }
}
char outBuff[buff_size];
int outPtr;

inline void putChar(const char &C) {
    outBuff[outPtr++] = C;
    if (outPtr == buff_size) {
        fwrite(outBuff, 1, buff_size, stdout);
        outPtr = 0;
    }
}

inline  void write(int X) {
    static char digs[10];
    int n = 0, q;
    do {
        q = X / 10;
        digs[n++] = X - (q << 1) - (q << 3) + 48;

        X = q;
    } while (X);
    while (n--) {
        putChar(digs[n]);
    }
    putChar(' ');

}

struct _arc{int cost, destinatie;} arc;
struct nod{vector<_arc> v;} v[50001];

struct cmp
{   inline bool operator()(_arc a1,_arc a2)  {return (a1.cost>a2.cost);}
};

vector<_arc> h;
bool viz[50001];
int sol[50001];int n, m;

int main()
{   int i, j, a, b, c;

    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    fread(buff,  1,buff_size, stdin);
    read(n);read(m);


    for(i=2;i<=n;i++)   sol[i]=INF;sol[1]=0;
    for(i=1;i<=m;i++)
    {
        read(a),read(b),read(c);
        arc.destinatie = b;
        arc.cost = c;
        v[a].v.push_back(arc);
    }



    for(i=0; i< v[1].v.size(); i++)
    {h.push_back(v[1].v[i]);sol[v[1].v[i].destinatie] = v[1].v[i].cost;}
    viz[1]=1;
    make_heap(h.begin(), h.end(), cmp);


    while(!h.empty())
    {   arc = h.front();
        pop_heap(h.begin(), h.end(), cmp);
        h.pop_back();
        if(arc.cost <= sol[arc.destinatie])
            sol[arc.destinatie] = arc.cost;
        if(!viz[arc.destinatie]){
        viz[arc.destinatie] = true;
        for(i=0; i< v[arc.destinatie].v.size(); i++)
        {

            if(!viz[v[arc.destinatie].v[i].destinatie])
            {
                v[arc.destinatie].v[i].cost += arc.cost;
                h.push_back(v[arc.destinatie].v[i]);
                push_heap(h.begin(), h.end(), cmp);
            }
        }}
    }

    for(i=2; i<=n; i++)
        if(sol[i] ==INF) write(0);
        else             write(sol[i]);

fwrite(outBuff, 1, outPtr, stdout);
}