Cod sursa(job #2865720)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 9 martie 2022 09:41:59
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

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

const int infinity = 0x3f3f3f3f;

struct Edge
{
    int destination;
    int cost;

    inline bool operator < (const Edge& other) const
    {
        return cost > other.cost;
    }
};

int n, m;
vector <Edge> graph[50005];
priority_queue <Edge> heap;
int distances[50005];

void Dijkstra(int start)
{
    memset(distances, infinity, sizeof(distances));
    distances[1] = 0;
    Edge startingEdge = {start, 0};
    heap.push(startingEdge);

    while (!heap.empty())
    {
        Edge currEdge = heap.top();
        heap.pop();

        for (Edge edge : graph[currEdge.destination])
        {
            if (distances[edge.destination] <= edge.cost + distances[currEdge.destination])
            {
                continue;
            }
            distances[edge.destination] = edge.cost + distances[currEdge.destination];
            edge.cost = edge.cost + distances[currEdge.destination];
            heap.push(edge);
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;
        Edge newEdge = {b, c};
        graph[a].push_back(newEdge);
    }

    Dijkstra(1);

    for (int i = 2; i <= n; i++)
    {
        fout << distances[i] << ' ';
    }
    fout << '\n';
}