Cod sursa(job #2858881)

Utilizator CiuiGinjoveanu Dragos Ciui Data 28 februarie 2022 15:40:04
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <cassert>
#include <vector>
#include <set>
using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
 
const int MAX_SIZE = 50005;
const int MAX_SUM = 1000001;
 
vector<pair<int, int>> graph[MAX_SIZE];
int costs[MAX_SIZE];
 
void findMinimumCosts(int peaks) {
    for (int i = 2; i <= peaks; ++i) {
        costs[i] = MAX_SUM;
    }
    set<pair<int, int>> positions;
    positions.insert(make_pair(0, 1));
    while (!positions.empty()) {
        int currentPeak = positions.begin()->second;
        positions.erase(positions.begin());
        for (pair<int, int> nextElement : graph[currentPeak]) {
            int nextPeak = nextElement.first;
            int nextCost = nextElement.second;
            if (costs[nextPeak] > costs[currentPeak] + nextCost) {
                if (costs[nextPeak] != MAX_SUM) {
                    positions.erase(positions.find(make_pair(costs[nextPeak], nextPeak)));
                }
                costs[nextPeak] = costs[currentPeak] + nextCost;
                positions.insert(make_pair(costs[nextPeak], nextPeak));
            }
        }
    }
    
    for (int i = 2; i <= peaks; ++i) {
        if (costs[i] == MAX_SUM) {
            costs[i] = 0;
        }
        fout << costs[i] << " ";
    }
}

int main() {
    int peaks, arches;
    fin >> peaks >> arches;
    for (int i = 0; i < arches; ++i) {
        int start, end, cost;
        fin >> start >> end >> cost;
        graph[start].push_back(make_pair(end, cost));
    }
    findMinimumCosts(peaks);
}