Cod sursa(job #3197447)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 26 ianuarie 2024 20:38:02
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <vector>
#include <climits>
#include <queue>

using namespace std;

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

const int DIM = 50010;
typedef pair<int, int> Pair;

int n, m, x, y, c;
int cost[DIM];
vector<pair<int, int>> l[DIM];
priority_queue<Pair, vector<Pair>, greater<>> pq;
bool visited[DIM];

void dijkstra(int start) {
    cost[start] = 0;
    pq.emplace(cost[start], start);
    while (!pq.empty()) {
        int node = pq.top().second;
        pq.pop();

        if (visited[node]) continue;
        visited[node] = true;

        for (auto adjElem : l[node]) {
            int adjNode = adjElem.first;
            int adjCost = adjElem.second;
            if (!visited[adjNode] && cost[adjNode] > cost[node] + adjCost) {
                cost[adjNode] = cost[node] + adjCost;
                pq.emplace(cost[adjNode], adjNode);
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        l[x].emplace_back(y, c);
    }

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

    for (int i = 2; i <= n; i++)
        fout << cost[i] << ' ';

    return 0;
}