Cod sursa(job #2878746)

Utilizator CiuiGinjoveanu Dragos Ciui Data 27 martie 2022 15:24:06
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <algorithm>
#include <iostream>
#include <cstring>
#include <fstream>
#include <cassert>
#include <vector>
#include <set>
#include <queue>
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;
    }
    priority_queue<pair<int, int>> positions;
    positions.push(make_pair(0, 1));
    while (!positions.empty()) {
        int currentPeak = positions.top().second;
        int currentCost = -positions.top().first;
        positions.pop();
        if (currentCost == costs[currentPeak]) {
            for (pair<int, int> nextElement : graph[currentPeak]) {
                int nextPeak = nextElement.first;
                int nextCost = nextElement.second;
                if (costs[nextPeak] > costs[currentPeak] + nextCost) {
                    costs[nextPeak] = costs[currentPeak] + nextCost;
                    positions.push(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);
}