Cod sursa(job #2576458)

Utilizator Alex100Alexandru Mihai Alex100 Data 6 martie 2020 19:35:25
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
#define MAX 50100
#define INF 99999999
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
struct nod
{
    int x,cost;
};
vector<nod>g[MAX];
inline bool operator<(nod a,nod b)
{
    return a.cost>b.cost;
}
priority_queue<nod>pq;
bool uz[MAX];
int d[MAX];
int n,m;
void dijkstra(int node);
int main()
{
    int i,x,y,z;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>z;
        g[x].push_back({y,z});
    }
    dijkstra(1);
    for(i=2; i<=n; i++)
        if(d[i]==INF)
            fout<<0<<' ';
        else
            fout<<d[i]<<' ';
    return 0;
}
void dijkstra(int node)
{
    int vecin,costt,nodcrt,i;
    for(i=0; i<MAX; i++)
        d[i]=INF;
    pq.push({node,0});
    d[node]=0;
    uz[node]=1;
    while(!pq.empty())
    {
        nodcrt=pq.top().x;
        costt=pq.top().cost;
        uz[nodcrt]=0;
        pq.pop();
        for(i=0; i<g[nodcrt].size(); i++)
            if(d[g[nodcrt][i].x]>costt+g[nodcrt][i].cost)
            {
                d[g[nodcrt][i].x]=costt+g[nodcrt][i].cost;
                if(!uz[g[nodcrt][i].x])
                {
                    uz[g[nodcrt][i].x]=1;
                    pq.push({g[nodcrt][i].x,d[g[nodcrt][i].x]});
                }
            }
    }
}