Cod sursa(job #2858844)

Utilizator CiuiGinjoveanu Dragos Ciui Data 28 februarie 2022 15:24:36
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <cassert>
#include <vector>
#include <set>
using namespace std;
 
const int NMAX = 50005;
const int MAX_SUM = 1000001;
 
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
vector<pair<int, int>> graph[NMAX];
 
int dist[NMAX];
 
int main() {
    int n, m;
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int start, end, cost;
        fin >> start >> end >> cost;
        graph[start].push_back(make_pair(end, cost));
    }
    memset(dist, MAX_SUM, sizeof dist);
    dist[1] = 0;
    set<pair<int, int>> positions;
    positions.insert(make_pair(0, 1));
    while (!positions.empty()) {
        int node = positions.begin()->second;
        positions.erase(positions.begin());
        for (pair<int, int> next : graph[node]) {
            int to = next.first;
            int cost = next.second;
            if (dist[to] > dist[node] + cost) {
                if (dist[to] != MAX_SUM) {
                    positions.erase(positions.find(make_pair(dist[to], to)));
                }
                dist[to] = dist[node] + cost;
                positions.insert(make_pair(dist[to], to));
            }
        }
    }
    for (int i = 2; i <= n; ++i) {
        if (dist[i] == MAX_SUM) {
            dist[i] = 0;
        }
        fout << dist[i] << ' ';
    }
}