Cod sursa(job #2829453)

Utilizator Mihai_EduardMihai Eduard Mihai_Eduard Data 8 ianuarie 2022 17:05:03
Problema Algoritmul lui Dijkstra Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int NMAX=50005;
const int inf=2e9;

int N, M, d[NMAX];
vector<pair<int,int>> g[NMAX];
struct minHeap{
    int v[NMAX]={}, p[NMAX]={}, L=0;
    int top()
    {
        return v[1];
    }
    void push(int nod)
    {
        L++;
        v[L]=nod;
        p[nod]=L;
        int poz=L;
        while(poz>1 and d[v[poz]]<d[v[poz/2]]){
            swap(v[poz],v[poz/2]);
            swap(p[v[poz]],p[v[poz/2]]);
            poz=poz/2;
        }
    }
    void pop()
    {
        swap(v[1],v[L]);
        swap(p[v[1]],p[v[L]]);
        L--;
        p[v[1]]=0;
        int poz=1;
        while(poz*2+1<=L and (d[v[poz*2]]<d[v[poz]] or d[v[poz*2+1]]<d[v[poz]])){
            if(d[v[poz*2]]<d[v[poz*2+1]]){
                swap(v[poz*2],v[poz]);
                swap(p[v[poz*2]],p[v[poz]]);
                poz=poz*2;
            }
            else{
                swap(v[poz*2+1],v[poz]);
                swap(p[v[poz*2+1]],p[v[poz]]);
                poz=poz*2+1;
            }
        }
        if(poz*2==L and d[v[poz*2]]>d[v[poz]]){
            swap(v[poz],v[poz*2]);
            swap(p[v[poz]],p[v[poz*2]]);
        }
    }
    void update(int nod)
    {
        int poz=p[nod];
        while(poz>1 and d[v[poz]]<d[v[poz/2]]){
            swap(v[poz],v[poz/2]);
            swap(p[v[poz]],p[v[poz/2]]);
            poz=poz/2;
        }
    }
};
minHeap heap;

void Dijkstra(int sursa)
{
    for(int i=1;i<=N;i++)
        d[i]=inf;
    d[sursa]=0;
    int x;
    heap.push(sursa);
    while(heap.L!=0){
        x=heap.top();
        heap.pop();
        for(auto next: g[x]){
            if(d[x]+next.second<d[next.first]){
                d[next.first]=d[x]+next.second;
                if(heap.p[next.first]==0)
                    heap.push(next.first);
                else
                    heap.update(next.first);
            }
        }
    }
}

int main()
{
    fin>>N>>M;
    int x, y, z;
    for(int i=1;i<=M;i++){
        fin>>x>>y>>z;
        g[x].push_back({y,z});
    }

    Dijkstra(1);

    for(int i=2;i<=N;i++)
        if(d[i]==inf)
            fout<<0<<' ';
        else
            fout<<d[i]<<' ';

    fin.close();
    fout.close();
    return 0;
}