Cod sursa(job #2958127)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 24 decembrie 2022 19:32:57
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 5e4;
const int INF = 2e9;

struct NodeCost{

    int node, cost;

    bool operator < (const NodeCost other) const {

        return cost > other.cost;

    }
};

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

priority_queue <NodeCost> pq;

void Dijkstra(int s)
{
    for(int i = 1; i <= N; i++)
        dist[i] = INF;

    pq.push({s, 0});

    while(!pq.empty())
    {
        int currentNode = pq.top().node;
        int currentDist = pq.top().cost;
        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.cost});
    }
}

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

    for(int i = 1; i <= M; i++) {

        int a, b, c; fin >> a >> b >> c;
        g[a].push_back({b, c});

    }

    Dijkstra(1);

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

    return 0;
}