Cod sursa(job #2661024)

Utilizator IRadu1529Radu Ionescu IRadu1529 Data 21 octombrie 2020 09:13:24
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <cmath>
#include <queue>

using namespace std;

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

struct muchie
{
    int el;
    long long int distanta;

    muchie(int el, long long int distanta)
        : el(el), distanta(distanta)
    {
    }
};

struct comp
{
    bool operator()(muchie const& p1, muchie const& p2)
    {
        return p1.distanta > p2.distanta;
    }

};

struct nod
{
    int s, d;
    long long int cost;
};

int main()
{
    int n, m, pp, a, b, c;

    fin >> n >> m;
    pp = 1;
    vector<vector<nod> > liste(n + 1, vector<nod>());

    vector<long long int> distanta(n + 1, 20000000001);

    distanta[pp] = 0;

    muchie p(pp, 0);

    for (int i = 0; i < m; i++)
    {
        fin >> a >> b >> c;

        nod aux, aux2;

        aux.s = a;

        aux2.s = b;

        aux.d = b;

        aux2.d = a;

        aux.cost = c;

        aux2.cost = c;

        liste[a].push_back(aux);

        liste[b].push_back(aux2);
    }

    priority_queue<muchie, vector<muchie>, comp> coada;

    coada.push(p);

    while (!coada.empty())
    {
        muchie top = coada.top();

        for (int i = 0; i < liste[top.el].size(); i++)
            if (distanta[liste[top.el][i].d] > distanta[top.el] + liste[top.el][i].cost)
            {
                distanta[liste[top.el][i].d] = distanta[top.el] + liste[top.el][i].cost;

                muchie x(liste[top.el][i].d, distanta[liste[top.el][i].d]);

                coada.push(x);
            }

        coada.pop();
    }

    for (int i = 2; i <= n; i++)
    {
        if (distanta[i] == 20000000001)
            fout << "0 ";

        else
            fout << distanta[i] << " ";
    }
}