Cod sursa(job #2722857)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 13 martie 2021 12:39:35
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 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(int _NODE, int _COST)
    {
        node = _NODE;
        cost = _COST;
    }
};

struct pqElement
{
    int node;
    int cost;

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

    pqElement(int _NODE, 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 cost[50001];

bool used[50001];

vector < edge > adj[50001];

void read()
{
    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));
    }
}

void solve()
{
    priority_queue < pqElement, vector < pqElement >, pqCompare > pq;

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

    cost[1] = 0;
    pq.push(pqElement(1, 0));

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

        if (used[node])
            continue;

        used[node] = true;

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

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

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

int main()
{
    read();
    solve();
    return 0;
}