Cod sursa(job #2671530)

Utilizator AvramDanielAvram Daniel AvramDaniel Data 12 noiembrie 2020 11:42:59
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include<bits/stdc++.h>
using namespace std;

#define N 50010
#define M 5e9

long long heap[N*2], L = 1,n,m, dist[N];
vector<int>v[N];
vector<int>d[N];
bool viz[N];

void heap_push(int pos){
    if(pos == 1 || dist[heap[pos]]> dist[heap[pos/2]])
        return;
    else{
        swap(heap[pos], heap[pos/2]);
        heap_push(pos/2);
        return;
    }
}

void heap_equilibrate(int pos){
    if(pos*2 > L) return;
    if(dist[heap[pos]] > dist[heap[pos*2]] && (dist[heap[pos*2]] < dist[heap[pos*2 + 1]] || pos*2+1 > L)){
        swap(heap[pos], heap[pos*2]);
        heap_equilibrate(pos*2);
        return;
    }
    if(pos*2 + 1 <=L && dist[heap[pos]] > dist[heap[pos*2 + 1]]){
        swap(heap[pos],heap[pos*2+1]);
        heap_equilibrate(pos*2 + 1);
        return;
    }
    return;
}


int main(){

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

    cin>>n>>m;
    for(int i = 0;i<m;i++){
        int a,b,c;
        cin>>a>>b>>c;
        v[a].push_back(b);
        v[b].push_back(a);
        d[a].push_back(c);
        d[b].push_back(c);
    }

    for(int i = 2;i<=n;i++){
        dist[i] = M;
    }

    heap[L] = 1;
    dist[0] = M;
    while(heap[1] != 0){
        int curr = heap[1];
        heap[1] = 0;
        heap_equilibrate(1);
        viz[curr] = 1;
       // cout<<'\n'<<curr<<": ";
        for(int i = 0; i<v[curr].size();i++){
            int next = v[curr][i];
            int next_dist = d[curr][i];
            if(!viz[next]){
                dist[next] = min(dist[next], dist[curr]+next_dist);
                heap[L] = next;
                heap_push(L);
                L++;
               // cout<<next<<' ';
                L++;
            }
        }
    }

    for(int i = 2;i<=n;i++)
        cout<<dist[i]<<' ';


    return 0;
}