Cod sursa(job #2758971)

Utilizator Tudor_1808Tudor Ioan Popescu Tudor_1808 Data 14 iunie 2021 18:21:22
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

struct ura
{
    int varf,cost;
};

int v[50001], h[50001], poz[50001];

int n,nh,m;

vector <ura> s[50001];

void schimbare(int x, int y)
{
    swap(h[x],h[y]);
    poz[h[x]]=x;
    poz[h[y]]=y;
}

void urcare(int p)
{
    while(p>1 && v[h[p]] < v[h[p/2]]){
        schimbare(p,p/2);
        p/=2;
    }
}

void coborare(int p)
{
    int fs=2*p;
    int fd=2*p+1;
    int bun=p;

    if(fs<=nh && v[h[fs]]<v[h[bun]])
        bun=fs;
    if(fd<=nh && v[h[fd]]<v[h[bun]])
        bun=fd;
    if(bun!=p){
        schimbare(p,bun);
        coborare(bun);
    }
}

void stergere(int p)
{
    if(p==nh)
        nh--;
    else{
        schimbare(p,nh);
        poz[h[nh--]]=-1;
        urcare(p);
        coborare(p);
    }
}

void f(int x)
{
    for(int i=1;i<=n;i++){
        v[i]=1000000001;
        h[++nh]=i;
        poz[i]=nh;
    }
    v[x]=0;
    while(nh>0){
        int val;
        val=h[1];
        stergere(1);
        for(auto p:s[val]){
            int y,c;
            y=p.varf;
            c=p.cost;
            if(v[val]+c<v[y]){
                v[y]=v[val]+c;
                urcare(poz[y]);
            }
        }
    }
}

int main()
{
    in>>n>>m;
    for(int i=0;i<m;i++){
        int x,y,c;
        in>>x>>y>>c;
        s[x].push_back((ura){y,c});
    }
    f(1);

    for(int i=2;i<=n;i++)
        if(v[i]!=1000000001)
            out<<v[i]<<' ';
        else
            out<<0<<' ';
    return 0;
}