Cod sursa(job #3199859)

Utilizator vlad414141414141Vlad Ionescu vlad414141414141 Data 2 februarie 2024 18:53:04
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 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()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    cin >> n >> m;
    for (int i=1;i<=n;++i)
        d[i]=inf;
    for (int i=0;i<m;++i)
    {
        cin >> 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]+g[cur.vecin][t].cost<d[g[cur.vecin][t].vecin]&&!viz[g[cur.vecin][t].vecin])
            {
                d[g[cur.vecin][t].vecin]=d[cur.vecin]+g[cur.vecin][t].cost;
                nod atx; atx.vecin=g[cur.vecin][t].vecin;atx.cost=d[g[cur.vecin][t].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()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    read();
    dijkstra(1);
    afis();
    return 0;
}