Cod sursa(job #2367182)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 5 martie 2019 09:17:10
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int INF = 1e9 + 5;
const int NMAX = 50000 + 5;

struct NodeCost
{
    int node, cost;

    bool operator < (const NodeCost other) const
    {
        return cost > other.cost;
    }
};

int N, M;
int dist[NMAX];
vector <NodeCost> g[NMAX];
priority_queue <NodeCost> pq;

int main()
{
    fin >> N >> M;

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

    int x, y, z;

    for(int i = 1; i <= M; i++)
    {
        fin >> x >> y >> z;
        g[x].push_back({y, z});
    }

    pq.push({1, 0});

    while(!pq.empty())
    {
        int currentNode = pq.top().node;
        int currentCost = pq.top().cost;
        pq.pop();

        if(dist[currentNode] != INF)
            continue;

        dist[currentNode] = currentCost;

        for(auto it : g[currentNode])
            if(dist[it.node] == INF)
                pq.push({it.node, currentCost + it.cost});
    }

    for(int i = 2; i <= N; i++)
        fout << ((dist[i] == INF) ? 0 : dist[i]) << '\n';

    return 0;
}