Cod sursa(job #1875587)

Utilizator antanaAntonia Boca antana Data 11 februarie 2017 12:33:05
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <cstdio>
#include <cctype>
#include <vector>
#include <queue>

#define x first
#define y second
#define MAXN 50001
#define BUF (1<<17)
#define INF 0x3f3f3f3f

using namespace std;

vector <pair<int, int > > G[MAXN];

int pos = BUF, dist[MAXN], n, m;
char buf[BUF];

FILE *fin, *fout;

class compare{
    public:
    bool operator () (int &x, int &y) {
        return dist[x] > dist[y];
    }
};

priority_queue< int, vector <int>, compare >heap;

void dijkstra()
{
    int node, son, edge;
    unsigned int i;

    heap.push(1);
    dist[1] = 0;

    while(!heap.empty())
    {
        node = heap.top();
        heap.pop();

        for(i=0; i<G[node].size(); ++i)
        {
            son = G[node][i].x;
            edge = G[node][i].y;

            if(dist[son] > dist[node] + edge)
            {
                dist[son] = dist[node] + edge;
                heap.push(son);
            }
        }
    }
}

inline char getChar();
inline int getInt();

int main()
{
    fin  = fopen("dijkstra.in", "r");
    fout = fopen("dijkstra.out", "w");

    int i, x, y, z;

    n = getInt();
    m = getInt();

    for(i=1; i<=m; ++i)
    {
        x = getInt();
        y = getInt();
        z = getInt();

        G[x].push_back({y, z});
    }

    for(i=1; i<=n; ++i)
        dist[i] = INF;

    dijkstra();

    for(i=2; i<=n; ++i)
        fprintf(fout, "%d ", (dist[i] != INF ? dist[i] : 0));

    fclose(fin);
    fclose(fout);

    return 0;
}

inline char getChar()
{
    if(pos == BUF)
        pos = 0, fread(buf, 1, BUF, fin);
    return buf[pos++];
}

inline int getInt()
{
    int nr = 0;
    char c;

    c = getChar();
    while(!isdigit(c)) c = getChar();
    while(isdigit(c))
    {
        nr = nr*10 + c-'0';
        c = getChar();
    }

    return nr;
}