Cod sursa(job #3199847)

Utilizator vlad414141414141Vlad Ionescu vlad414141414141 Data 2 februarie 2024 18:45:15
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

#define inf 2147483647

using namespace std;

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

struct nod
{
    int vecin, cost;
    bool operator < (const nod&other) const
    {
        if (cost==other.cost)
            return vecin>other.vecin;
        return cost>other.cost;
    }
};

int n, m, x, y, d[50041], c;
bool viz[50041];

priority_queue<nod> q;
vector <nod> g[50041];

void read()
{
    fin >> n >> m;
    for (int i=1;i<=n;++i)
        d[i]=inf;
    for (int i=0;i<m;++i)
    {
        fin >> x >> y >> c;
        nod aux;
        aux.cost=c;aux.vecin=y;
        g[x].push_back(aux);
    }
}

void dijkstra(int top)
{
    d[top]=0;
    nod aux;aux.cost=0;aux.vecin=top;
    q.push(aux);
    while (!q.empty())
    {
        nod cur=q.top();
        viz[cur.vecin]=true;
        q.pop();
        for (int t=0;t<g[cur.vecin].size();++t)
        {
            int vecin=g[cur.vecin][t].vecin;
            int cost=g[cur.vecin][t].cost;
            if (d[cur.vecin]+cost<d[vecin]&&!viz[vecin])
            {
                d[vecin]=d[cur.vecin]+cost;
                nod atx; atx.vecin=vecin;atx.cost=d[vecin];
                q.push(atx);
            }
        }
    }
}

void afis()
{
    for (int i=2;i<=n;++i)
    {
        if (d[i]!=inf)
            fout << d[i] << " ";
        else
            fout << 0 << " ";
    }
}

int main()
{
    read();
    dijkstra(1);
    afis();
    return 0;
}