Cod sursa(job #2850557)

Utilizator VladTZYVlad Tiganila VladTZY Data 16 februarie 2022 23:17:48
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

#define NMAX 50005

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

typedef pair<int, int> pi;

int n, m, x, y, cost;
int dp[NMAX];
vector <pi> neighbours[NMAX];
priority_queue <pi, vector <pi>, greater<pi> > q;

void dijkstra(int start) {

    dp[start] = 0;
    q.push({0, start});

    while (!q.empty()) {
        int cost = q.top().first;
        int node = q.top().second;
        q.pop();

        if (dp[node] == cost) {

            for (auto neighbour : neighbours[node]) {
                int newNode = neighbour.first;
                int newCost = neighbour.second;

                if (cost + newCost < dp[newNode]) {

                    dp[newNode] = cost + newCost;
                    q.push({dp[newNode], newNode});
                }
            }
        }

    }
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++) {
        f >> x >> y >> cost;

        neighbours[x].push_back({y, cost});
    }

    for (int i = 1; i <= n; i++)
        dp[i] = INT_MAX;

    dijkstra(1);

    for (int i = 2; i <= n; i++) {

        if (dp[i] == INT_MAX)
            g << "0 ";
        else
            g << dp[i] << " ";
    }
    g << "\n";

    return 0;
}