Cod sursa(job #3295388)

Utilizator bogdan1479Luca Bogdan Alexandru bogdan1479 Data 5 mai 2025 08:57:41
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 5e4 + 1, INF = 1 << 29;

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

struct muchie
{
    int y, w;
    muchie(int yy = 0, int ww = 0): y(yy), w(ww) {}
};

int n, m, d[NMAX];
bool inq[NMAX];

class comp
{
public:
    bool operator()(int a, int b) const
    {
        return d[a] > d[b];
    }
};

vector<muchie> g[NMAX];
priority_queue<int, vector<int>, comp> q;

void citire()
{
    int x, y, c;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        g[x].push_back({y, c});
    }
}

void dijkstra(int nod)
{
    int crt, cost;
    d[nod] = 0;
    q.push(nod);
    inq[nod] = 1;
    while(!q.empty())
    {
        crt = q.top();
        q.pop();
        inq[crt] = 0;
        for(const muchie& mm : g[crt])
        {
            cost = d[crt] + mm.w;
            if(d[mm.y] > cost)
            {
                d[mm.y] = cost;
                if(!inq[mm.y])
                {
                    q.push(mm.y);
                    inq[mm.y] = 1;
                }
            }
        }
    }
}

int main()
{
    citire();
    for(int i = 1; i <= n; ++i) d[i] = INF;
    dijkstra(1);
    for(int i = 2; i <= n; ++i)
        if(d[i] == INF) fout << "0 ";
        else fout << d[i] << ' ';
    return 0;
}