Cod sursa(job #2812246)

Utilizator rARES_4Popa Rares rARES_4 Data 4 decembrie 2021 11:32:05
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include<climits>
using namespace std;
ifstream f ("dijkstra.in");
ofstream g ("dijkstra.out");
int n,m,x,y,c;
bool viz[50001];
vector<pair<int,int>>adiacenta[50001];
int costuri[50001];
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;
void citire()
{
    f >> n >> m;
    for(int i = 1; i<=m; i++)
    {
        f >> x >> y >> c;
        adiacenta[x].push_back({y,c});
    }
    for(int i = 1; i<=50000; i++)
        costuri[i] = INT_MAX;
}
void alg()
{
    costuri[1] = 1;
    q.push({1,1});
    while(!q.empty())
    {
        int nod = q.top().second;
        int cost = q.top().first;
        q.pop();
        if(viz[nod]== 1)
            continue;
        viz[nod] = 1;
        for(auto x:adiacenta[nod])
        {
            if(costuri[x.first]>x.second+cost)
            {
                costuri[x.first]=x.second+cost;
                q.push({costuri[x.first],x.first});
            }
        }
    }
}
void afisare()
{
    for(int i = 2; i<=n; i++)
    {
        if (costuri[i] == INT_MAX)
        {
            g << 0 << " ";
        }
        else
            g << costuri[i]-1<< " ";
    }
}
int main()
{
    citire();
    alg();
    afisare();
}