Cod sursa(job #3304763)

Utilizator Gabriel_DaescuDaescu Gabriel Florin Gabriel_Daescu Data 26 iulie 2025 23:11:52
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <fstream>
#include <vector>
#define NMAX 50002
#define INF (1<<30)
using namespace std;
ifstream  fin("dijkstra.in");
ofstream fout("dijkstra.out");
int N,M,H;
vector<int> heap(NMAX,0),pozitie(NMAX,0),cost(NMAX,INF);
vector<pair<int,int>>graph[NMAX];

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

    int A,B,C;
    for(int i=1; i<=M; i++)
    {
        fin>>A>>B>>C;
        graph[A].push_back({B,C});
    }
}

void urcare(int poz)
{
    while(poz/2>=1 && cost[heap[poz]]<cost[heap[poz/2]])
    {
        swap(pozitie[heap[poz]],pozitie[heap[poz/2]]);
        swap(heap[poz],heap[poz/2]);
        poz=poz/2;
    }
}

void coborare(int poz)
{
    while(2*poz<=H)
    {
        int r=2*poz;
        if(r+1<=H && cost[heap[r+1]]<cost[heap[r]])
        {
            r++;
        }

        if(cost[heap[r]]<cost[heap[poz]])
        {
            swap(pozitie[heap[poz]],pozitie[heap[r]]);
            swap(heap[poz],heap[r]);
            poz=r;
        }
        else
        {
            break;
        }
    }
}

void adaugare_heap(int nod)
{
    H++;
    heap[H]=nod;
    pozitie[nod]=H;
    urcare(H);
}

void eliminare_minim()
{
    pozitie[heap[1]]=0;
    pozitie[heap[H]]=1;
    heap[1]=heap[H];
    H--;
    coborare(1);
}

int main()
{
    citire();

    H=0;
    cost[1]=0;
    adaugare_heap(1);

    while(H)
    {
        int nod=heap[1];
        eliminare_minim();

        for(int j=0; j<graph[nod].size(); j++)
        {
            int next_nod=graph[nod][j].first;
            if(cost[next_nod]>cost[nod]+graph[nod][j].second)
            {
                cost[next_nod]=cost[nod]+graph[nod][j].second;

                if(!pozitie[next_nod])
                {
                    adaugare_heap(next_nod);
                }
                else
                {
                    urcare(pozitie[next_nod]);
                }
            }
        }

    }

    for(int i=2; i<=N; i++)
    {
        if(cost[i]==INF)
        {
            cost[i]=0;
        }
        fout<< cost[i] <<  " ";
    }
    fout<< "\n";

    return 0;
}