Cod sursa(job #2806563)

Utilizator amalia.gemanGeman Aamalia amalia.geman Data 22 noiembrie 2021 19:35:29
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>
#define inf 100000
#define Nmax 50005
using namespace std;

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

priority_queue <pair<int,int>> q;
vector <pair<int,int>> muchii[Nmax];
bool viz[Nmax];
int N, M, dist[Nmax];

void Read()
{
    fin >> N >> M;

    for(int i = 1; i <= M; ++i)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        muchii[x].push_back({cost,y});
    }

    // initial presupunem fiecare distanta ca fiind infinit
    for(int i = 2; i <= N; ++i)
        dist[i] = inf;
}


void Dijkstra(int s)
{
    q.push({0,s});
    viz[s] = 1;
    dist[s] = 0;

    while(!q.empty())
    {
        int nod = q.top().second; // nodul curent
        // int cost = q.top().first; // costul
        q.pop();

        viz[nod] = 0;

        for(auto i : muchii[nod])
        {
            int vecin = i.second;
            int cost = i.first;

            if(dist[nod] + cost < dist[vecin])
            {
                dist[vecin] = dist[nod] + cost;
                if(!viz[vecin])
                {
                    viz[vecin] = 1;
                    q.push({dist[vecin],vecin});
                }
            }
        }
    }
}

void Afisare()
{
    for(int i = 2; i <= N; ++i)
    {
        if(dist[i] != inf)
            fout << dist[i] << " ";
        else
            fout << 0 << " ";
    }
}

int main()
{
    Read();
    Dijkstra(1);
    Afisare();

    return 0;
}