Cod sursa(job #2848169)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 12 februarie 2022 10:42:17
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

struct edge
{
    int node;
    int cost;

    edge()
    {
        node = 0;
        cost = 0;
    }

    edge(const int _NODE, const int _COST)
    {
        node = _NODE;
        cost = _COST;
    }
};

struct pqElement
{
    int node;
    int cost;

    pqElement()
    {
        node = 0;
        cost = 0;
    }

    pqElement(const int _NODE, const int _COST)
    {
        node = _NODE;
        cost = _COST;
    }
};

class pqCompare
{
    public:
        bool operator () (const pqElement& a, const pqElement& b)
        {
            return a.cost > b.cost;
        }
};

const int INF = 2e9;

int n, m;

int dist[50001];

bool used[50001];

vector < edge > adj[50001];

void dijkstra(const int source)
{
    priority_queue < pqElement, vector < pqElement >, pqCompare> pq;


    for (int i = 1; i <= n; i++)
    {
        dist[i] = INF;
        used[i] = false;
    }

    pq.push(pqElement(source, 0));
    dist[source] = 0;

    while (!pq.empty())
    {
        int node = pq.top().node;
        int cost = pq.top().cost;
        pq.pop();

        if (used[node])
            continue;

        used[node] = true;

        for (auto it : adj[node])
            if (cost + it.cost < dist[it.node])
            {
                dist[it.node] = cost + it.cost;

                if (!used[it.node])
                    pq.push(pqElement(it.node, dist[it.node]));
            }
    }
}

int main()
{
    f >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int a, b, c; f >> a >> b >> c;
        adj[a].push_back(edge(b, c));
    }

    dijkstra(1);

    for (int i = 2; i <= n; i++)
        if (dist[i] != INF)
            g << dist[i] << " ";
        else
            g << 0 << " ";

    return 0;
}