Cod sursa(job #1983192)

Utilizator FrequeAlex Iordachescu Freque Data 21 mai 2017 14:22:07
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

struct edge
{
    int nod;
    int cost;

    bool operator< (const edge & arg) const
    {
        return arg.cost < cost;
    }

    edge(int _nod = 0, int _cost = 0)
    {
        nod = _nod;
        cost = _cost;
    }
};

const int NMAX = 50000 + 5;
const int INF = INT_MAX;

vector <edge> g[NMAX];
priority_queue <edge> pq;

int n, m;
int drum[NMAX];
bool vis[NMAX];

void read()
{
    int x, y, c;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        g[x].push_back(edge(y, c));
    }
}

void dijkstra(int node)
{
    int x;
    for (int i = 1; i <= n; ++i)
        drum[i] = INF;
    drum[node] = 0;

    pq.push(edge(node, drum[node]));
    while (!pq.empty())
    {
        x = pq.top().nod;
        pq.pop();
        if (!vis[x])
        {
            vis[x] = true;
            for (int i = 0; i < g[x].size(); ++i)
                if (drum[g[x][i].nod] > drum[x] + g[x][i].cost)
                {
                    drum[g[x][i].nod] = drum[x] + g[x][i].cost;
                    if (!vis[g[x][i].nod])
                        pq.push(edge(g[x][i].nod, drum[g[x][i].nod]));
                }
        }
    }
}

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

int main()
{
    read();
    dijkstra(1);
    write();
    return 0;
}