Dijkstra Algorithm

The Dijkstra Algorithm, named after its creator, Edsger W. Dijkstra, is a widely-used graph traversal algorithm that finds the shortest path between a starting node and all other nodes in a weighted graph. Often used in routing and navigation applications, Dijkstra's algorithm works by iteratively selecting the node with the smallest known distance from the starting node, and updating the distances of its neighboring nodes based on the edge weights connecting them. This process is repeated until all nodes have been visited or the shortest path to the destination node has been determined. In order to efficiently keep track of distances and visited nodes, the algorithm typically uses a priority queue data structure. Initially, the starting node is assigned a distance of zero, while all other nodes are assigned an infinite distance. As the algorithm progresses, it extracts nodes with the smallest distance from the priority queue, marking them as visited and updating the distances of their neighbors. This ensures that nodes are visited in the order of their proximity to the starting node, guaranteeing the discovery of the shortest path. Once the destination node has been visited or all nodes have been processed, the path can be reconstructed by tracing back from the destination node to the starting node via the shortest path tree formed during the algorithm's execution.
#include <queue>
#include <vector>
#include <cstdio>
#include <iostream>
using namespace std;
#define INF 10000010
vector<pair<int, int>> graph[5 * 100001];
int dis[5 * 100001];
int dij(vector<pair<int, int>> *v, int s, int *dis)
{
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    // source distance to zero.
    pq.push(make_pair(0, s));
    dis[s] = 0;
    int u;
    while (!pq.empty())
    {
        u = (pq.top()).second;
        pq.pop();
        for (vector<pair<int, int>>::iterator it = v[u].begin(); it != v[u].end(); it++)
        {
            if (dis[u] + it->first < dis[it->second])
            {
                dis[it->second] = dis[u] + it->first;
                pq.push(make_pair(dis[it->second], it->second));
            }
        }
    }
}
int main()
{
    int m, n, l, x, y, s;
    // n--> number of nodes , m --> number of edges
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        // input edges.
        scanf("%d%d%d", &x, &y, &l);
        graph[x].push_back(make_pair(l, y));
        graph[y].push_back(make_pair(l, x)); // comment this line for directed graph
    }
    // start node.
    scanf("%d", &s);
    // intialise all distances to infinity.
    for (int i = 1; i <= n; i++)
        dis[i] = INF;
    dij(graph, s, dis);

    for (int i = 1; i <= n; i++)
        if (dis[i] == INF)
            cout << "-1 ";
        else
            cout << dis[i] << " ";
    return 0;
}

LANGUAGE:

DARK MODE: