Cod sursa(job #2415291)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 25 aprilie 2019 18:40:50
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

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

struct NodeDist
{
    int node, dist;

    bool operator < (const NodeDist other) const
    {
        return dist > other.dist;
    }
};

int N, M;
vector <NodeDist> g[NMAX + 5];

int dist[NMAX + 5];
priority_queue <NodeDist> pq;

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

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

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

    pq.push({1, 0});

    while(!pq.empty())
    {
        int currentNode = pq.top().node;
        int currentDist = pq.top().dist;
        pq.pop();

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

        dist[currentNode] = currentDist;

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

    for(int i = 2; i <= N; i++)
        if(dist[i] != INF)
            fout << dist[i] << ' ';
        else
            fout << 0 << ' ';

    return 0;
}